容器视图及其一些问题

Container View and some problems with it

我刚从 Swift 开始,我可以解决这个问题 我不知道如何 运行 来自 ViewController 的 ViewController2 中的函数。

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 = "!"
    }
}

获取对嵌入在容器视图中的视图控制器的引用的最简单方法是在 (prepare(for segue:sender:) 中这样做。

当您在故事板中设置容器视图时,您会看到一个将包含视图控制器链接到包含视图控制器的转场。这是一个 embed segue,它将在包含视图控制器加载后立即触发(但在 viewDidLoad 完成后)。您可以使用此 segue 获取对目标的引用(这将是您的 ViewController2 实例)并将其存储在 属性 中。您无需对 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
        }
    }
}