Why I Write My Views Programmatically (And Not In A StoryBoard)

For the majority of people, storyboards are introduced at an early stage of learning iOS development. Most tutorials and videos reference view controllers and view objects from the storyboard because of the ease of dragging an object onto the screen, and developers can depend on that object appearing on the screen at run-time. For many projects that beginners work through, storyboards make the development process quick and simple. This is the case for most apps that are aren’t dynamic in nature because the developer knows where each UI component will be placed on the screen, and its size will remain static.

What happens when a user clicks a button that is supposed the shrink a view or transition new view components? You could designate an action and outlet to the view object, but changing the constraints across multiple user interactions can cause trouble if the constraints were initialized by ctrl-dragging to anchor points. Most of the time, new developers aren’t keeping track of the constraints for each view object because the constraints aren’t explicitly labeled in code, but rather hidden in the xml file of the storyboard or represented by the blue lines that are a pain to hover over when there are several view objects on the screen. To make the UI development process faster and more organized, I write my views in code.

At first it might look like a lot of unnecessary code that could be replaced with storyboard objects, but programmatic views are documented in the code itself. If the developer needs to change the title of a button, instead of going to the storyboard, finding the correct editor tab, and then scrolling down until they find the title editor, they can find the view container code block and quickly reference the setTitle() method. This saves time on the amount of clicks, and it may not seem like such a big deal, but when working on an app with several dozen views, locating the correct view object will be a lot more efficient than searching through storyboards. Another advantage is that the constraints of a view object can be referenced when written in code so that developers can ensure the object isn’t abnormally sized at run-time when a button size needs to increase or be repositioned on the screen.

Like most things, writing views in code takes practice to get efficient at, but in the end it will save you valuable time in the development lifecycle, and give you a much deeper understanding of the UIKit framework. For any iOS developer looking to build a more complex and dynamic app, programmatic views can give you a major advantage in delivering a scalable and beautiful mobile application.