Call UIViewController method from UIViewController

2019-08-02 04:07发布

In my app I have a “main” ViewController. On app launch in the body of its viewDidAppear, I retrieve the value of a UserDefaults boolean: if the user is not logged in, I present modally another viewcontroller this way:

self.performSegue(withIdentifier:"loginView", sender:self)

This launches modally AuthViewController, a viewcontroller that contains a “Container View”, a region of AuthViewController that includes a UIPageViewController (AuthPageViewController).

This last one has two “pages”: LoginViewController and RegisterViewController.

More than a thousand words

LoginViewController is used to login users: once the user is logged in I want to call a function (no matter what it does) on the main ViewController.

So, to summarize, I’m in LoginViewController and I want to call a method of ViewController.

While trying a solution I discovered the following:

  • I can’t get a reference to presentingViewController because LoginViewController has not been opened directly from ViewController. Moreover, AuthViewController was not launched with present(_:animated:completion:) but with self.performSegue as I said before;
  • instantiating a ViewController from LoginViewController and calling a method works but it’s not a good idea;
  • NSNotification works like a charm;
  • apparently delegates aren’t working or I’m missing something about their implementation in the contest of this app;

Can you help me understand how to call a ViewController method from my LoginViewController? Code examples are very well received, but I appreciate any advice.

标签: ios swift3
1条回答
趁早两清
2楼-- · 2019-08-02 04:59

Let me explain it with code of how to use delegate in this case,

First you need create a delegate in LoginViewController like this

protocol LoginViewControllerDelegate: class {
    func goToContent(animated:Bool)
}

then create a variable for delegate like this

weak var delegate: LoginViewControllerDelegate?

Now in you ViewController you have to assign the delegate like this in your prepare prepareforsegue method, as you are using segue like this

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if segue.identifier == "yourSegueIdentifier" {
        let nextScene =  segue.destination as! LoginViewController
        nextScene.delegate = self
    }
}

and implement that method like this

func goToContent(animated: Bool) {
    print("test")
}

in this way you are able to call goToContent from LoginViewController

查看更多
登录 后发表回答