ios - 如何识别来自 UITableView 的 UITableViewCell 中多个按钮的点击 - Swift 4

标签 ios swift uitableview uibutton

我想实现 UITableView 我想在每个 UITableViewCell 中有 3 个按钮。我想为每个按钮执行不同的操作。如何确定按下哪个按钮,然后获取所选单元格的对象(索引行)?

UIViewController

 func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let show=shows[indexPath.row]
    let cell = tableView.dequeueReusableCell(withIdentifier: "ShowCell") as!
    ShowCell

    cell.setShow(show: show)
    return cell
}

UITableViewCell
@IBOutlet weak var graphButton: FlatButton!
@IBOutlet weak var buyButton: FlatButton!
@IBOutlet weak var reviewButton: FlatButton!


func setShow(show :StubHubEvent ){


    let url = URL(string: show.imageurl)!

    showImageView.af_setImage(withURL: url)
    showImageView.contentMode = .scaleAspectFill
    showImageView.clipsToBounds = true
    nameLabel.text = show.title
    dateLabel.text = show.time

最佳答案

在 UIviewcontroller 而不是 UITableViewCell 中实现您的按钮操作,在 cellforRow 内创建目标,并为每个目标添加标签以识别用户按下了哪个按钮。例如

  func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let show=shows[indexPath.row]
    let cell = tableView.dequeueReusableCell(withIdentifier: "ShowCell") as!
    ShowCell

     cell.graphButton.tag = indexPath.row
     cell.buyButton.tag = indexPath.row
     cell.reviewButton.tag = indexPath.row

     cell.graphButton?.addTarget(self, action: #selector(self.graphButtonClicked(_:)), for: .touchUpInside)
     cell.buyButton?.addTarget(self, action: #selector(self.buyButtonClicked(_:)), for: .touchUpInside)          
     cell.reviewButton?.addTarget(self, action: #selector(self.reviewButtonClicked(_:)), for: .touchUpInside)


    cell.setShow(show: show)
    return cell
}

并像处理 Action 一样
 @objc func buyButton( _ sender: UIButton) {
       print("buyButton Action Found the index of \(sender.tag)")

}

@objc func graphButtonClicked( _ sender: UIButton) {
       print("graphButtonClicked Action Found the index of \(sender.tag)")

}

@objc func reviewButtonClicked( _ sender: UIButton) {
       print("reviewButtonClicked Action Found the index of \(sender.tag)")

}

选项 2

如果您想使用委托(delegate)模式在 UItableviewcell 类中执行按钮操作,请引用 duplicate answer

关于ios - 如何识别来自 UITableView 的 UITableViewCell 中多个按钮的点击 - Swift 4,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55056384/

相关文章:

ios - 从未在 UICollectionView 中调用 prepareForSegue

iOS 7 后台传输服务在 3 分钟后停止

swift - wholemodule 优化模式保留了哪些断言?

iphone - 通过 tableview 添加 View (UITableViewController)

ios - 应用程序在调用 'tableView endUpdates' 时崩溃

ios - 两个 TableView 一个数据源?

ios - 我的应用程序因为缺少 "significant account-specific functionality from Google"而被拒绝

ios - 如何以编程方式在 Swift 的 UITableView 中选择一行

ios - iOS中如何检测音量变化?

ios - 在大型 UIView 上绘制占用大量内存