0

I have a table view that its cells have a button in themselves and these buttons should open a view with an unique id. So I need to passing an argument to my buttons but with addTarget property I just can call function without any parameter.

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
...
    cell.editButton.addTarget(self, action: #selector(goToEdit(id:)), for: .touchUpInside)
}

func goToEdit(id: String) {
    let edit = EditAdViewController(editingAdId: id)
    self.navigationController?.pushViewController(edit, animated: true)
}

Is there any way to refer an action with some parameters to a button? Thanks everyone :)

p.yarandi
  • 59
  • 1
  • 11

2 Answers2

0

Maybe you can try to link your button to a @IBAction and use params[indexPath.row].

To get the indexPath:

var cell = sender.superview() as? UITableViewCell 
var indexPath: IndexPath? = yourTableView.indexPath(for: cell!)
  • unfortunately #selector can't get any parameter – p.yarandi Sep 23 '17 at 21:22
  • try to link you button to a @IBAction and use params[indexPath.row]. to get the indexPath: var cell = sender.superview() as? UITableViewCell var indexPath: IndexPath? = yourTableView.indexPath(for: cell!) –  Sep 23 '17 at 21:30
  • @LucasMoraes Don't post code in comments. [Edit] your answer will all relevant details. – rmaddy Sep 23 '17 at 21:44
0

You can try adding delegate functions to your custom UITableViewCell.

For example, I have a button inside this custom tableViewCell:

PickupTableViewCell.swift

    import UIKit

protocol PickupTableViewCellDelegate: NSObjectProtocol {
    func pickupTableViewCell(userDidTapPickup pickup: Pickup, pickupTableViewCell: PickupTableViewCell)
}

class PickupTableViewCell: UITableViewCell {

    // MARK: - Properties

    @IBOutlet private weak var label_UserFullName: UILabel!
    ....

    // MARK: - Functions
    // MARK: IBAction

    @IBAction func pickup(_ sender: Any) {
        self.delegate?.pickupTableViewCell(userDidTapPickup: self.pickup, pickupTableViewCell: self)
    }
}

Then in I conform my controller via the UITableViewDataSource (cellForRow) and of course implement the delegate function of my tableViewCell.

HomeViewController.swift

// MARK: - UITableViewDataSource

extension HomeViewController: UITableViewDataSource {
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let pickupTVC = tableView.dequeueReusableCell(withIdentifier: R.reuseIdentifier.pickupTableViewCell)!
        pickupTVC.delegate = self
        pickupTVC.pickup = self.pickups[indexPath.section]

        return pickupTVC
    }
}

// MARK: - PickupTableViewCellDelegate

extension HomeViewController: PickupTableViewCellDelegate {
    func pickupTableViewCell(userDidTapPickup pickup: Pickup, pickupTableViewCell: PickupTableViewCell) {
        // Do something
    }
}
Glenn Posadas
  • 12,555
  • 6
  • 54
  • 95