[英]Access ViewController from action in TableViewCell
I have ViewController with TableView.我有带有 TableView 的 ViewController。 In each cell of this TableView there are few buttons (so I can't use didSelectRow).
在这个 TableView 的每个单元格中有几个按钮(所以我不能使用 didSelectRow)。
I need to get parent ViewController from action when buttons are pressed.按下按钮时,我需要从操作中获取父 ViewController。 So I add this function to my custom cell class:
所以我将此函数添加到我的自定义单元格类中:
@IBAction func editBtnPressed (_ sender: Any) {
}
I need to get to self in order to add some subviews to it.我需要进入 self 以便向它添加一些子视图。 How can I access root ViewController as self ?
如何以self身份访问 root ViewController ?
I guess you should do it by creating property of your controller in cell class and assign property value when after creating cell in cellForRowAtIndexPath method.我想你应该通过在单元类中创建控制器的属性来实现,并在 cellForRowAtIndexPath 方法中创建单元后分配属性值。
For example:例如:
in cell class在细胞类
weak var yourController : YourViewController?
in cellForRowAtIndexPath
在
cellForRowAtIndexPath
cell.yourController = self
then you can access the YourViewController
in editBtnPressed
action.然后您可以在
editBtnPressed
操作中访问YourViewController
。
But i suggest you to do by creating button action programmatically in your controller class.但我建议您通过在控制器类中以编程方式创建按钮操作来完成。 that's the good approach.
这是个好方法。
for example:例如:
class YourCellClass: UITableViewCell {
@IBOulet var myBtn: UIbutton!
...
}
Yourcontroller class你的控制器类
in cellForRowAtIndexPath
在
cellForRowAtIndexPath
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = self.tableView.dequeueReusableCell(withIdentifier: cellReuseIdentifier) as! YourCellClass
cell.myButton.addTarget(self, action: #selector(self. editBtnPressed), for: .touchUpInside)
and in editBtnPressed
并在
editBtnPressed
func editBtnPressed (_ sender: Any) {
// you can access controller here by using self
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.