Search code examples
iosswiftxcodeuilabeluicontainerview

Container View and some problems with it


Im just starting with Swift and i can get past this problem i dont know how to run the function inside the ViewController2 from ViewController.

import UIKit

class Main: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    }

    @IBAction func onButtonPressed(_ sender: Any) {
        performSegue(withIdentifier: "newSegue", sender: self)
    }

}

class ViewController: UIViewController {

    let SecondViewController = ViewController2()

    override func viewDidLoad() {
        super.viewDidLoad()
        SecondViewController.changeText()
        // Do any additional setup after loading the view, typically from a nib.
    }

}

class ViewController2: UIViewController {

    @IBOutlet weak var label1: UILabel!
    @IBOutlet weak var label2: UILabel!
    @IBOutlet weak var label3: UILabel!
    @IBOutlet weak var label4: UILabel!
    @IBOutlet weak var label5: UILabel!
    @IBOutlet weak var label6: UILabel!

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    }

    func changeText() {
        label1.text = "hi"
        label2.text = "how"
        label3.text = "are"
        label4.text = "you"
        label5.text = "doing"
        label6.text = "!"
    }
}

Solution

  • The simplest way to get a reference to the view controller that is embedded in a container view is to do so in (prepare(for segue:sender:).

    When you set up a container view in the storyboard, you will see a segue that links the containing view controller to the contained view controller. This is an embed segue that will fire just after the containing view controller is loaded (but after viewDidLoad has completed). You can use this segue to get a reference to the destination (which will be your instance of ViewController2) and store it in a property. You don't need to make any changes to your ViewController2 class.

    class ViewController: UIViewController {
    
        var secondViewController: ViewController2?
    
        override func viewDidLoad() {
            super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        }
    
        override func viewWillAppear(_ animated: Bool) {
            super.viewWillAppear(animated)
            self.secondViewController?.changeText()
        }
    
        override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
            if let destVC = segue.destination as? ViewController2 {
                self.secondViewController = destVC
            }
        }
    }