When I override viewWillTransition in a child view controller, the given size is incorrect. When running the example below on an iPad 9th Generation, I expect the width of the RedVC to be 200, and the width of the BlueVC to be 880 when rotating from portrait to landscape. As you can see in the print statements, the view frame is correct, but the size in the function parameter is incorrect. What am I missing?
Output:
viewWillTransition(to:with:) View Frame: 200.0 Size Width: 1080.0 RedVC
viewWillTransition(to:with:) View Frame: 880.0 Size Width: 1080.0 BlueVC
viewWillTransition(to:with:) View Frame: 1080.0 Size Width: 1080.0 ViewController
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let redVC = RedVC()
redVC.view.translatesAutoresizingMaskIntoConstraints = false
addChild(redVC)
view.addSubview(redVC.view)
redVC.didMove(toParent: self)
let blueVC = BlueVC()
addChild(blueVC)
view.addSubview(blueVC.view)
blueVC.didMove(toParent: self)
blueVC.view.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
redVC.view.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor),
redVC.view.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor),
redVC.view.leadingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.leadingAnchor),
redVC.view.widthAnchor.constraint(equalToConstant: 200),
blueVC.view.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor),
blueVC.view.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor),
blueVC.view.leadingAnchor.constraint(equalTo: redVC.view.safeAreaLayoutGuide.trailingAnchor),
blueVC.view.trailingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.trailingAnchor),
])
}
override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
super.viewWillTransition(to: size, with: coordinator)
coordinator.animate(alongsideTransition: nil) { [weak self] _ in
print(#function, "View Frame: \(self?.view.frame.width ?? 0) ", "Size Width: \(size.width)", "ViewController")
}
}
}
class BlueVC: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .systemBlue
}
override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
super.viewWillTransition(to: size, with: coordinator)
coordinator.animate(alongsideTransition: nil) { [weak self] _ in
print(#function, "View Frame: \(self?.view.frame.width ?? 0) ", "Size Width: \(size.width)", "BlueVC")
}
}
}
class RedVC: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .systemRed
}
override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
super.viewWillTransition(to: size, with: coordinator)
coordinator.animate(alongsideTransition: nil) { [weak self] _ in
print(#function, "View Frame: \(self?.view.frame.width ?? 0) ", "Size Width: \(size.width)", "RedVC")
}
}
}