UIViewController 包含通知

UIViewController containment notifications

我对 UIViewController 包含有疑问。为了简单起见,我做了一个示例项目并定义了 SecondViewController class.

class SecondViewController: UIViewController {

override func viewDidLoad() {
    super.viewDidLoad()
    self.view.backgroundColor = UIColor.black
    NSLog("In second controller")

    // Do any additional setup after loading the view.
}

override func willTransition(to newCollection: UITraitCollection, with coordinator: UIViewControllerTransitionCoordinator) {
    NSLog("Transitioning in second controller")
  }
 }

在第一个控制器中,我执行以下操作:

class ViewController: UIViewController {

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

    let secondController = SecondViewController()
    addChild(secondController)
    view.addSubview(secondController.view)
    secondController.view.frame = self.view.bounds
    secondController.didMove(toParent: self)
}

override func willTransition(to newCollection: UITraitCollection, with coordinator: UIViewControllerTransitionCoordinator) {
    NSLog("Transitioning in first controller")
   }
 }

当我 运行 程序时,它 运行 是日志:

2018-09-28 19:11:15.491211+0400 ViewContainment[3897:618645] In second controller
2018-09-28 19:11:17.254221+0400 ViewContainment[3897:618645] Transitioning in first controller

问题:

  1. 这是否意味着所有 UIViewController 通知都将由第一个视图控制器处理,而不会向第二个视图控制器发送任何通知?

  2. 将第二个视图控制器中的按钮单击操作添加到第一个视图控制器中的选择器是否安全?

来自 Apple 的文档 (https://developer.apple.com/documentation/uikit/uicontentcontainer/1621511-willtransition):

If you override this method in your own objects, always call super at some point in your implementation so that UIKit can forward the trait changes to the associated presentation controller and to any child view controllers. View controllers forward the trait change message to their child view controllers.

因此请确保您在 ViewController 中的函数执行此操作:

override func willTransition(to newCollection: UITraitCollection, with coordinator: UIViewControllerTransitionCoordinator) {
    super.willTransition(to: newCollection, with: coordinator)
    NSLog("Transitioning in first controller")
}

问题 2:否。使用协议/委托模式允许子视图控制器中的操作与父视图控制器中的函数/方法进行通信。