Self Taught Swift: Adding Elements Without Using Storyboard

It’s much easer than you think.

Phil Andrews
2 min readJan 22, 2016

--

When you drag and drop a UIButton onto a storyboard, aside from the styling and sizing aspects of the button, it’s exactly the same as writing these two lines in viewDidLoad():

let button = UIButton()
self.view.addSubview(view: button)

If you want that button to look exactly like a button that you would drag onto a storyboard:

let button = UIButton()
button.frame.size = CGSize(width: 88.0, height: 44.0)
button.center = self.view.center
button.text = "Button"

self.view.addSubview(view: button)

When you want your button to do something when it’s tapped:

let button = UIButton()
button.frame.size = CGSize(width: 88.0, height: 44.0)
button.center = self.view.center
button.text = "Button"
button.addTarget(self, action: Selector("buttonWasPressed"), forControlEvents: .TouchUpInside)
self.view.addSubview(view: button)

Let’s break down addTarget. We’ll say you have a function inside of your viewController that looks like this:

func buttonWasPressed() {    print(“You pressed the button”)}

--

--