NEW: Learn SwiftUI with my free YouTube video series! >>

How to make your user interface in code

Swift version: 5.0

Paul Hudson    @twostraws   

Creating your user interface in code gives you the flexibility to build things conditionally, to step through problems in a debugger, to re-use components more easily, and to monitor changes more closely in source control. On the flip side, you lose features like easy segues, static cell design in table views, the ability to preview on multiple devices simultaneously, and more.

However, I’m going to assume you’ve already decided you want to make your UI in code, so let’s take a look at how it’s done:

Often you’ll see code like this inside the viewDidLoad() method of a view controller:

backgroundColor = UIColor(white: 0.9, alpha: 1)

let stackView = UIStackView()
stackView.translatesAutoresizingMaskIntoConstraints = false
stackView.spacing = 10
view.addSubview(stackView)

stackView.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor).isActive = true
stackView.leadingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.leadingAnchor).isActive = true
stackView.trailingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.trailingAnchor).isActive = true
stackView.axis = .vertical

let notice = UILabel()
notice.numberOfLines = 0
notice.text = "Your child has attempted to share the following photo from the camera:"
stackView.addArrangedSubview(notice)

let imageView = UIImageView(image: shareImage)
stackView.addArrangedSubview(imageView)

let prompt = UILabel()
prompt.numberOfLines = 0
prompt.text = "What do you want to do?"
stackView.addArrangedSubview(prompt)

for option in ["Always Allow", "Allow Once", "Deny", "Manage Settings"] {
    let button = UIButton(type: .system)
    button.setTitle(option, for: .normal)
    stackView.addArrangedSubview(button)
}

That’s a complex user interface, but if you’re writing that sort of thing inside your viewDidLoad() method you’re making a terrible mistake. In fact, if you write that kind of code and you aren’t just prototyping or learning something, then you lose all rights to complain that your view controllers are massive later on.

All the code above – literally all of it – is view code, and needs to be treated as such. It is not controller code, and even with Apple’s muddied definition of MVC it is not view controller code either. It’s view code, and belongs in a subclass of UIView.

This change is trivial to make: you copy all that code, paste it into a new subclass of UIView called SharePromptView, then change the class of your view controller to your new subclass.

The final SharePromptView class should look something like this:

class SharePromptView: UIView {
    override init(frame: CGRect) {
        super.init(frame: frame)
        createSubviews()
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        createSubviews()
    }

    func createSubviews() {
        // all the layout code from above
    }
}

All UIView subclasses must implement init(coder:), but as you’re creating your UI in code you will also need to add init(frame:). The createSubviews() method is there to support both.

Thanks to that custom UIView subclass you can now take a huge amount of code out of your view controller:

class ViewController: UIViewController {
    var shareView = SharePromptView()

    override func loadView() {
        view = shareView
    }

    override func viewDidLoad() {
        super.viewDidLoad()
    }
}

Having a dedicated shareView property allows you to access any properties you declare inside SharePromptView without having to keep casting view.

SPONSOR Meet the new Instabug – more than just bug reporting! We help you build better apps and minimize your debugging time. With each bug report, we automatically capture details like network requests, repro steps, and session details. Get real-time crash reports with stack trace details and session data to help you catch and fix issues easily. And with our customizable in-app surveys, you’ll gather insightful user feedback and much more. Instabug is the fastest and easiest way to release with confidence. Start your free trial now! Start your free trial now!

Available from iOS 9.0 – learn more in my book Swift Design Patterns

Did this solution work for you? Please pass it on!

Other people are reading…

About the Swift Knowledge Base

This is part of the Swift Knowledge Base, a free, searchable collection of solutions for common iOS questions.

MASTER SWIFT NOW
Buy Testing Swift Buy Practical iOS 12 Buy Pro Swift Buy Swift Design Patterns Buy Swift Coding Challenges Buy Server-Side Swift (Vapor Edition) Buy Server-Side Swift (Kitura Edition) Buy Hacking with macOS Buy Advanced iOS Volume One Buy Advanced iOS Volume Two Buy Hacking with watchOS Buy Hacking with tvOS Buy Hacking with Swift Buy Dive Into SpriteKit Buy Swift in Sixty Seconds Buy Objective-C for Swift Developers Buy Beyond Code

Was this page useful? Let me know!

Average rating: 4.0/5

Click here to visit the Hacking with Swift store >>