ios - 自定义单元格中的按钮索引
问题描述
我创建了一个包含按钮的自定义单元格,我需要创建从这个按钮到其他 VC 的 segue,但首先,我想用那个 segue 推送一个对象。
我已经尝试使用 cell.button.tag,但我没有成功。
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "showMap" {
let mapVC = segue.destination as! MapViewController
//guard let indexPath = tableView.indexPathForSelectedRow else { return }
mapVC.place = places[] // <- "here I need index of button in cell"
}
}
解决方案
而不是使用,而是通过in以编程方式segue
处理。navigation
closure
UITableViewCell
class CustomCell: UITableViewCell {
var buttonTapHandler: (()->())?
@IBAction func onTapButton(_ sender: UIButton) {
self.buttonTapHandler?()
}
}
在上面的代码中,我创建了buttonTapHandler
一个-a ,只要点击内部closure
,就会调用它。button
cell
现在,在cellForRowAt
您的单元格中,dequeue
设置buttonTapHandler
.CustomCell
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "CustomCell", for: indexPath) as! CustomCell
cell.buttonTapHandler = {[weak self] in
if let mapVC = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "MapViewController") as? MapViewController {
mapVC.place = places[indexPath.row]
self?.navigationController?.pushViewController(mapVC, animated: true)
}
}
return cell
}
在上面的代码中,buttonTapHandler
当被调用时,将push
创建一个新的实例MapViewController
以及相关place
的基于indexPath
.
推荐阅读
- javascript - 如何更新文本输入值以使用货币格式
- python - 在不同的集合中添加列
- ios - 从 paypal ios sdk swift 获取送货地址和发票号码
- ios - 在 Swift 中将带有“\n”的数组元素合并到字符串中
- sql - 在 oracle 中检查模式表空间的使用情况
- javascript - 在茉莉花测试中模拟声明 const
- python - 如何确保所有文件在 Python 中共享相同的结构?
- java - 使用 selenium,java 在 chrome 驱动程序中禁用 css 渲染
- ruby-on-rails - Heroku 部署失败 | 宝石安装 json -v '1.8.1'
- react-native - 在 React Native 中使用 requestAnimationFrame