【问题标题】:Add target for button in table view cells在表格视图单元格中为按钮添加目标
【发布时间】:2017-09-23 21:08:17
【问题描述】:

我有一个表格视图,它的单元格本身有一个按钮,这些按钮应该打开一个具有唯一 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)
}

有没有办法将带有一些参数的动作引用到按钮?谢谢大家:)

【问题讨论】:

标签: swift uitableview addtarget


【解决方案1】:

您可以尝试将委托函数添加到您的自定义 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
    }
}

【讨论】:

    【解决方案2】:

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

    获取索引路径:

    var cell = sender.superview() as? UITableViewCell 
    var indexPath: IndexPath? = yourTableView.indexPath(for: cell!)
    

    【讨论】:

    • 很遗憾#selector 无法获取任何参数
    • 尝试将您的按钮链接到@IBAction 并使用参数[indexPath.row]。获取 indexPath: var cell = sender.superview() as? UITableViewCell var indexPath: IndexPath? = yourTableView.indexPath(for: cell!)
    • @LucasMoraes 不要在 cmets 中发布代码。 Edit你的答案将是所有相关的细节。
    猜你喜欢
    • 2014-02-01
    • 1970-01-01
    • 2011-01-27
    • 2016-07-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多