This question already has answers here:
swift: how to get the indexpath.row when a button in a cell is tapped?
(14个答案)
去年关门了。
我在我的custom
我需要做的是将数据传递给另一个viewController,但重要的是要知道按钮是在哪个单元格上按下的,所以如何告诉我的方法prepare
按了哪个单元格的按钮?我是个初学者,我已经找了两天的解决方案,但还没有找到
在表视图控制器中,添加一个类级变量:
然后,表视图单元格设置变为:
在准备阶段:
(14个答案)
去年关门了。
我在我的custom
@IBOutlet weak var cellButton: UIButton!
类中添加了一个buttontableViewCell
,在我的tableView
控制器中添加了一个button的操作 @IBAction func cellButtonTap(_ sender: UIButton) {
performSegue(withIdentifier: "goToMap" , sender: self)
}
我需要做的是将数据传递给另一个viewController,但重要的是要知道按钮是在哪个单元格上按下的,所以如何告诉我的方法prepare
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "goToMap"...//HERE I DON'T KNOW HOW TO DO
}
按了哪个单元格的按钮?我是个初学者,我已经找了两天的解决方案,但还没有找到
最佳答案
你可以用“回拨”结束。。。
class MyTableViewCell: UITableViewCell {
var didButtonTapAction : (()->())?
@IBAction func cellButtonTap(_ sender: UIButton) {
// call back closure
didButtonTapAction()?
}
}
在表视图控制器中,添加一个类级变量:
var tappedIndexPath: IndexPath?
然后,表视图单元格设置变为:
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "MyCell", for: indexPath) as! MyTableViewCell
// set labels, colors, etc in your cell
// set a "call back" closure
cell.didButtonTapAction = {
() in
print("Button was tapped in cell at:", indexPath)
// you now have the indexPath of the cell containing the
// button that was tapped, so
// call performSegue() or do something else...
self.tappedIndexPath = indexPath
performSegue(withIdentifier: "goToMap" , sender: self)
}
return cell
}
在准备阶段:
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "goToMap" {
// do what you need based on the row / section
// of the cell that had the button that was tapped, such as:
if let vc = segue.destination as? MyMapViewController {
vc.myData = self.dataArray[self.tappedIndexPath.row]
}
}
}