Create an iOS UIButton Completely in Code Using Swift
Published in
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
- UIViews need constraints before they can appear properly (top, leading, trailing, height, width, pinning, etc)
- NSLayoutConstraint.activate will let you add a whole bunch of constraints at once and activate them
- Handling button taps is easy with UIButton.addTarget; it will allow you to specify an Objective-C selector function to deal with the tap