Creating a button with UIKit seems easy enough, right? We have all the properties inherited from UIButton()
and creating a pill / capsule style button should be a matter of setting layer.cornerRadius
to 50, right?!
WRONG
Unbeknownst to me, it was not as straightforward or as easy as I thought, but it’s also not that hard either!
Here’s what we want to achieve:
LET'S GET STARTED
The easy way to create the pill button is by taking 1/2 of the height! Let’s do this!
Initiate the button by assigning a new button variable to the UIButton() class in which you will inherit built-in button properties. This button will be globally accessible.
let playButton - UIButton()
In your button constraints, you should set your heightAnchor
and widthAnchor
to the desired size you want it to.
// Always do this when setting your own constraints (replace with your button variable); set to false
playButton.translatesAutoresizingMaskIntoConstraints = false
//set height + width constraints
playButton.heightAnchor.constraint(equalToConstant: 50).isActive = true
playButton.widthAnchor.constraint(equalToConstant: 44).isActive = true
Now that we have the height and width for the button determined, let’s style the button so that we can achieve the rounded pill/capsule look!
It’s very simple and all we have to do is take 1/2 of the height for the corner radius.
Since our height is 50
we will set the cornerRadius
to 25
playButton.layer.cornerRadius = 50
EASY PEASY!
Here's some additional example of different heights. Remember, the corner radius would be 1/2 of the height to get this rounded look.
When heightAnchor is set to 50:
When heightAnchor is set to 75:
When heightAnchor is set to 100: