Sometimes, you will want a view controller to always have the same fixed bounds, such as, for example, the width of the screen. Suppose that you have designed a nib with the view defined into it, and you want to make sure that whenever you create a new instance of this controller, the size will always be correct.
You may be tempted to write the following code:
class OtherBadController: UIViewController {
init() {
super.init(nibName: "OtherBadController", bundle: nil)
print("before")
let width = UIScreen.main.bounds.width
self.view.frame = CGRect(x: 0, y: 0, width: width, height: width)
print("after")
}
override func viewDidLoad() {
super.viewDidLoad()
print("loaded")
}
}
// Output:
before
loaded
after
In this example, where we have accessed the view inside the constructor, we can see that the view loading takes place within the constructor, as loaded is logged before after.
You will want to avoid this order at all costs, and ensure that your view controller constructors are properly completed before any view loading occurs. When loading complex view controller hierarchies, this can lead to serious performance problems, and can render your apps unresponsive.