ios - UIViewController 包含通知

标签 ios uiviewcontroller uikit

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

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")
  }
 }

在第一个 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 通知都将由第一个 View Controller 处理,而不会向第二个 View Controller 发送任何通知?

  2. 将第二个 View Controller 中的按钮点击操作添加到第一个 View Controller 中的选择器是否安全?

最佳答案

来自 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 中的 func 执行此操作:

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

问题 2:否。使用协议(protocol)/委托(delegate)模式允许 subview Controller 中的操作与父 View Controller 中的函数/方法进行通信。

关于ios - UIViewController 包含通知,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52558330/

相关文章:

ios - 如何在WKWebview上添加UIButton?

ios - Swift 从第一响应者那里辞职 TextView

ios - 在实例化 ViewController 之前更改/修改运行时用户定义的属性

ios - 显示模态 Controller 时与呈现 Controller 交互

iphone - CAGradientLayer,无法很好地调整大小,旋转时撕裂

iOS代码组织模式

iphone - UIWebview 大小限制

ios - UITableView的 subview 永远不会显示

ios - 更改viewController iOS4.3后崩溃

ios - 修复导致 sigabort