moonvader
moonvader

Reputation: 21091

Access ViewController from action in TableViewCell

I have ViewController with TableView. In each cell of this TableView there are few buttons (so I can't use didSelectRow).

I need to get parent ViewController from action when buttons are pressed. 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. How can I access root ViewController as self?

Upvotes: 2

Views: 3159

Answers (1)

Sahil
Sahil

Reputation: 9226

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.

For example:

in cell class

weak var yourController : YourViewController?

in cellForRowAtIndexPath

cell.yourController = self

then you can access the YourViewController in editBtnPressed action.

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

    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

func editBtnPressed (_ sender: Any) {
 // you can access controller here by using self

}

Upvotes: 5

Related Questions