Reputation: 163
I've been building my view controllers programmatically by setting a custom view in the loadView()
method. While changing my root view controller in AppDelegate
to a specified view controller, I've noticed that the view controller does not display it's subviews properly laid out, if it even gets displayed. Using the view debugger, I see that the views are seen as being in the view hierarchy but they are no where to be found, so I end up with blank view controller. What's odd is that when I instead present the view controller from another view controller, only then is it properly laid out and all views are visible. My view controllers all follow the same creation shown below.
class ViewController: UIViewController {
private var rootView: View? {
get { return self.viewIfLoaded as? View ?? .none }
set (view) { self.view = view }
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
init() {
super.init(nibName: nil, bundle: nil)
}
override func viewDidLoad() {
super.viewDidLoad()
}
override func loadView() {
self.rootView = View()
}
}
And here is how I am creating my custom views for my view controllers
class View: UIView {
// Lazy declare views here
fileprivate var shouldSetupConstraints = true
override init(frame: CGRect) {
super.init(frame: frame)
setupView()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setupView()
}
override func updateConstraints() {
if(shouldSetupConstraints) {
// Adding constraints here
shouldSetupConstraints = false
}
super.updateConstraints()
}
func setupView() {
// Adding subviews here
}
}
Here is how I am setting the root view controller in my AppDelegate
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
window = UIWindow(frame: UIScreen.main.bounds)
window?.backgroundColor = Palette.backgroundColor
window?.rootViewController = MyViewController()
window?.makeKeyAndVisible()
return true
}
I expect my programmatically laid out view controllers to be displayed properly while being set as the root view controller, but instead the views are not visible or not laid out properly. They are only displaying correctly when the view controller is presented by another view controller.
Upvotes: 0
Views: 412
Reputation: 163
Looks like this behavior was being caused by not setting
self.translatesAutoresizingMaskIntoConstraints = false
in setupView()
in my custom view.
Upvotes: 1