Swift — Creating a view without storyboard

Jack Ngai
Jack Ngai
Jul 28, 2017 · 3 min read

I know it is easy to build a single view application with storyboard. Xcode practically sets up everything for you. I will let you google the reasons why you should stop using storyboard. I’m just going to show you how to set one up to match what Apple creates for you.

You don’t need this.

After creating the project, go into Project->Targets->Deployment Info, delete the word “Main” from Main Interface.

Press ⌘ + 1 if you don’t see the Project Navigator for step 1.

Next, delete Main.storyboard.

Sayonara!

Now, you need add the code to draw the window, make it key and visible, and set ViewController.swift as the root view controller in AppDelegate.swift to create the view. This is the code:

window = UIWindow(frame: UIScreen.main.bounds)

window?.makeKeyAndVisible()

window?.rootViewController = ViewController()

There are Windows on Apple.

Feel free to read up on Apple’s documentation on UIWindow to learn about the methods used in the code.

Now, go to ViewController.swift and change the background to white so it matches what Apple gave you in storyboard.

view.backgroundColor = .white

Don’t like white? Change it to your favorite (ui)color

At this point, you are done. If you run the app now, you will have a blank white screen in the simulator, exactly the same thing Apple provides you with storyboard.

carte blanche

But you ask, how do I add buttons, text fields, image views? All programmatically. I won’t cover all that in this post, but here’s a small snippet of code to show you how to add a text field in ViewController.swift.

// In ViewController class, outside of any methods

let textField = UITextField(frame: CGRect(x: 0, y: 10, width: 200, height: 40))

// In ViewDidLoad() method

textField.text = “Hello World”

view.addSubview(textField)

3 lines of code to create and display a text field

This is how it looks.

Simple, right?

That’s it. Of course there’s a lot more to it: Using layout anchors to set constraint; Changing the font type, font size and color; Adding targets. The list goes on. But this is a good start.

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade