我想实现 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/