Reputation: 6551
I have a doubt about UIViewController containment. For simplicity, I made a sample project and defined 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")
}
}
And in first controller, I do the following:
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")
}
}
When I run the program, it runs and here are the logs:
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
Questions:
Does that mean all the UIViewController notifications will be handled by first view controller, and no notifications will be sent to the second view controller?
Is it safe to add actions for button clicks in second view controller to selectors in first view controller?
Upvotes: 0
Views: 120
Reputation: 77647
From Apple's docs ( 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.
So make sure your func in ViewController
does this:
override func willTransition(to newCollection: UITraitCollection, with coordinator: UIViewControllerTransitionCoordinator) {
super.willTransition(to: newCollection, with: coordinator)
NSLog("Transitioning in first controller")
}
Question 2: No. Use protocol / delegate pattern to allow actions in the child view controller to communicate with funcs / methods in the parent view controller.
Upvotes: 1