Beardy Bear
Beardy Bear

Reputation: 123

How to call a a different view by code in xcode 7

I am new to xcode 7 and it would be great if you could help me with something.

I have two ViewControllers and I would like to call ViewController2 from ViewController1. I need to do that by code. (I would like to call it from the viewDidLoad()-function)

Thanks in advance

Upvotes: 0

Views: 51

Answers (1)

SeanRobinson159
SeanRobinson159

Reputation: 904

Depending on how you have the project and your navigation setup, here is one of the many ways to accomplish what I think you are asking.

If you are using Segues for navigation, in the ViewController1 (That initialized the navigation) you would override the prepareForSegue function cast your segue.destination as ViewController2 and set the property. Like this

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    super.prepare(for: segue, sender: sender)
    guard let viewController2 = segue.destination as? ViewController2 else { return }

    viewController2.propertyName = "Property Value"
}

Or, if you are wanting to instantiate ViewController2 in ViewController1 you could do this:

override viewDidLoad() {
    super.viewDidLoad()

    guard let viewController2 = self.storyboard?.instantiateViewController(withIdentifier: "ID for ViewController (set in the Storyboard)") as? ViewController2 else { return }
    viewController2.propertyName = "Property Value"

    self.present(viewController2, animated: true, completion: nil)
    // Or you could do if you want a full navigation, not just a modal.
    self.show(viewController2, sender: self)
}

If you are wanting to access each view controller, you could do something like this:

class ViewController2: UIViewController {
    weak var viewController1: ViewController1? //The 'weak' keyword is incredibly important so that you don't have a memory leak.

    override viewDidLoad() {
        self.viewController1.propertyName = "Property Value"
    }
}

Using the same steps as above, you can set the viewController1 property in the ViewController2 instance.

Now I hope that answers your question. Your question is a little vague, so I am shooting in the dark.

Upvotes: 1

Related Questions