Umit Kaya
Umit Kaya

Reputation: 5951

Protocol/delegate in Swift3 doesn't work

I have followed this tutorial to have delegate methods to update a value in my other class, but it does not even trigger it. Can you please tell me what i am doing wrong?

protocol myDelegate {
    func report(info:String)
}

class TypeFilterViewController: UIViewController, XLFormRowDescriptorViewController,
                                UITableViewDataSource, UITableViewDelegate {

    var delegate:myDelegate?

    func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
         self.delegate?.report("testValue")
         self.navigationController?.popViewControllerAnimated(true) 
    }
}

So, after i select the row item, i dismissed pushed view and display previous class.

class SearchRefinementsTypeCell: XLFormBaseCell, XLFormBaseCellSeparator, myDelegate {

    // Delegate method
    func report(info: String) {
        print("delegate: \(info)")
    }

    override func update() {
        super.update()
        let mc = TypeFilterViewController()
        mc.delegate = self

       self.headerLabel.text = //Value from TypeFilterViewController didSelectRow
    }

Thank you for all kind of helps.

Upvotes: 0

Views: 689

Answers (1)

alexburtnik
alexburtnik

Reputation: 7741

You clearly misunderstood the tutorial. Delegate pattern is useful when you want to delegate from a cell to view controller. You're doing the opposite: sending event from a viewController to a cell, which is pointless, since your viewController already has access to it's tableView, which in it's turn operates with it's cells.

Also you shouldn't use any ViewControllers inside cell class because it breaks MVC pattern. You should think of UITableViewCell and pretty much every UIView as of powerless objects which cannot decide anything by themselves, but can only delegate events to other smart guys, which do the logic by themselves (view controllers).

Now about your case: You have vc A and vc B, pushed over it. When a cell in B is pressed, you should send a callback to A, right? What you should do:

  1. B has a delegate which implements some protocol
  2. When A pushes B, it set's itself as a protocol: b.delegate = self
  3. When a cell is selected in B, you call delegate's method, which is implemented in A and passes a string into it.
  4. UI in A is updated.

Once again, cells must not know anything about any of your view controllers, they are just pawns. All logic should be handled between view controllers themselves.

Upvotes: 2

Related Questions