Call function in view controller from UITableViewC

2019-05-30 04:26发布

问题:

I have a problem which drives me nuts, how is it possible to invoke a function in a view controller from within a UITableViewCell. - I am doing that in Swift.

So I have a View Controller - called mainVC in this mainVC I have declared a tableView which holds a UITableViewCell (Custom/ Dynamic) in that tableView cell I want call a function which is declared in the mainVC. If I do like self.superview?.myFunc doesn't work.

I hope someone can help me...

回答1:

It is not as easy as that unfortunately. What you want to look into is NSNotificationCenter or even better: - Delegates. If you want a better understanding of Delegates I'd recommend this tutorial: http://www.raywenderlich.com/75289/swift-tutorial-part-3-tuples-protocols-delegates-table-views

If you don't want to read all that, I'll try my best to explain it here.

Let's say you have two view controllers: mainVC and otherVC.

Above the class definition in otherVC, add the following code:

protocol OtherVCDelegate {
   func cellClicked()
}

Inside the class in otherVC, add the following property:

var delegate: OtherVCDelegate?

In the didSelectRow (or where you execute the code), add the following code:

self.delegate?.cellClicked()

Now, back in mainVC: Make mainVC conform to this delegate by adding it to the class like this:

class MainViewController: UIViewController, DetailDelegate {
}

In MainViewController add the delegate function and insite that one put your function you want to execute:

func cellClicked() {
    println("Cell was clicked")
    myFunc()
}

The last thing you have to do is make MainViewController the delegate of OtherViewController. This has to be done where you access the otherVC from the mainVC. Let's say it is done in prepareForSegue:

if segue.identifier == "showDetail" {
       (segue.destinationViewController as DetailViewController).delegate = self
    }

It is a little bit complicated at first, but once you get a grasp of it it's a walk in the park.