Create an iOS UIButton Completely in Code Using Swift

Andrew
I am Become Coder, Creator of Code Things
1 min readApr 22, 2020

Written with Swift v5.2

Objective

Deciding it was time to embrace building views in code as as well using Interface Builder, I set myself the challenge to build a simple UIButton completely in code.

Here’s what I made:

In the interests of keeping things as simple as possible, I chose a minimal approach. I have a bigger demo in the works already!

And here’s the code that I came-up with for that above UIButton:

Key take-aways

  1. UIViews need constraints before they can appear properly (top, leading, trailing, height, width, pinning, etc)
  2. NSLayoutConstraint.activate will let you add a whole bunch of constraints at once and activate them
  3. Handling button taps is easy with UIButton.addTarget; it will allow you to specify an Objective-C selector function to deal with the tap

--

--

Andrew
I am Become Coder, Creator of Code Things

iOS Software Engineer. Punster extraordinaire. Part-time nerf herder.