0

I have a cell which I use in many different vc because I have my app divided in different categories but all use the same cell.

Now I have a button which should trigger the event to share it via other apps like whastapp or facebook. The problem is that depending on in which category you are you have a different view controller which will display the function. I can make it work with one but not with 10 different vc in just one cell.

I used an extension to get the parentviewController

extension UIView {
var parentViewController: HomeViewController? {
    var parentResponder: UIResponder? = self
    while parentResponder != nil {
        parentResponder = parentResponder!.next
        if parentResponder is UIViewController {
            return parentResponder as! HomeViewController!
        }
    }
    return nil
} 

This will obviously only work at the Home vc.

How can I work around this issue?

Zash__
  • 293
  • 4
  • 16

1 Answers1

1

You can use a protocol to handle your button action in the view controller:

protocol ShareEventDelegate: class {
    func didShareButtonSelected()
}

In your custom cell:

class CustomCell: UITableViewCell {
    weak var shareDelegate: ShareEventDelegate?

    func yourButtonAction() { 
       shareDelegate.didShareButtonSelected?()
    }
}

Then make your ViewControllers conform to the ShareEventDelegate, for example:

extension HomeViewController: ShareEventDelegate {
    func didShareButtonSelected() {
        // handle your action here
    }
}

And in cellForRow:

cell.shareDelegate = self
Francesco Deliro
  • 3,899
  • 2
  • 19
  • 24