0

我有一个表格视图,它的单元格本身有一个按钮,这些按钮应该打开一个具有唯一 ID 的视图。所以我需要将一个参数传递给我的按钮,但是有了addTarget属性我就可以在没有任何参数的情况下调用函数。

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)
}

有什么方法可以将带有某些参数的操作引用到按钮?感谢大家 :)

4

2 回答 2

0

您可以尝试将委托函数添加到您的自定义 UITableViewCell。

例如,我在这个自定义 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)
    }
}

然后在我通过我的控制器符合我的控制器 UITableViewDataSource (cellForRow),当然实现我的 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
    }
}
于 2017-09-23T21:39:26.193 回答
0

也许您可以尝试将您的按钮链接到 @IBAction 并使用 params[indexPath.row]。

要获取 indexPath:

var cell = sender.superview() as? UITableViewCell 
var indexPath: IndexPath? = yourTableView.indexPath(for: cell!)
于 2017-09-23T21:20:13.657 回答