swift - 在 TableView 单元格中添加按钮目标

标签 swift uitableview addtarget

我有一个 TableView ,它的单元格本身有一个按钮,这些按钮应该打开一个具有唯一 ID 的 View 。因此,我需要向按钮传递一个参数,但使用 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)
}

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

最佳答案

您可以尝试向自定义 UITableViewCell 添加委托(delegate)函数。

例如,我在此自定义 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) 来符合我的 Controller ,当然还实现了我的 tableViewCell 的委托(delegate)功能。

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

关于swift - 在 TableView 单元格中添加按钮目标,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46384309/

相关文章:

ios - UISearchController 结果 tableView 不适合窗口 IOS 8.1

ios - 创建全局 NSOperationQueue

ios - 当我尝试删除 UITableViewCell 时,出现此错误 : Invalid update: invalid number of rows in section 0, 但我似乎无法修复它

swift - iOS 9.0 以下的分段控件 addTarget() 崩溃应用程序

Swift:如何在 button.addTarget 中添加参数

ios - 如何仅针对 UIControlEvent.allEditingEvents 覆盖 UITextField 中的 addTarget?

ios - 在 iphone 6 中从后台重新打开时应用程序崩溃

ios - Alamofire 5 : Value of type 'Result<Data, AFError>' has no member 'value'

iphone - heightForRowAtIndexPath 用于更长的 NSString

uitableview - TableView :cellForRowAtIndexPath: in iOS Today Widget with UITableViewController called once