Sometimes I see code that sets up subviews in viewDidLoad() of a
view controller. Be a good citizen and don’t do that. If you have
to add something to a view, do it in a UIView subclass.
Here is how I implement view and controller code when I’m not using
Interface Builder.
The View
Let’s build a login view:
This code defines two text fields and a button and puts it onto the view
with the help of UIStackView (line 26
and 31). If you haven’t played with stack views yet, start now. They are
awesome!
Note that the layout constraints don’t define the vertical position of
the stack view on the view. We will add vertical constraints in the view
controller.
The View Controller
Here comes the view controller:
If you build your user interface in code you should override loadView(). Within
loadView() you
need to set the view property of the view controller. In this
example we additionally add a target to the login button.
Note the definition of the calculated property loginView. This is
done to allow the access of the loginView’s stackView in
viewWillLayoutSubviews().
The view controller can be presented within a navigation controller (and
in fact is in the demo project). To position the stack view in respect
to the bottom edge of the navigation bar we use the topLayoutGuide of
the view controller. This takes into account the navigation bar. This
means the code viewWillLayoutSubviews()
puts the stack view 8 points below the navigation bar.
The so defined login screen looks like this:\
You can find the sample code on
github. In the sample
project you can also find three other possibilities to define the layout
and in addition the version using Interface Builder.
If you enjoyed this post, then make sure you subscribe to my
feed.