UIKit: Rounded Views

Let’s start off this series of “Swift pills” with a simple yet frustrating-for-beginners technique to make a view’s corners rounded. Here is the code:

myView.layer.cornerRadius = 20
myView.layer.masksToBounds = true
Rounded Button

If you want a circular view, create a squared one in the interface builder and set its radius as half of its width (or height 🔲):

myView.layer.cornerRadius = myButton.frame.width * 0.5
myView.layer.masksToBounds = true
Circular Button

And last but not least, from iOS 11.0+ you can round only some specific corners:

myView.layer.cornerRadius = 20
myView.layer.maskedCorners = [
Rounded Button with masks

Each view in UIKit has a property layer of type CALayer that actually manages the rendering and has its own visual attributes that you can set such as background color, border and shadow.

I usually set this properties in the didSet property observer to avoid polluting the viewDidLoad method with visual customizations:

@IBOutlet weak var myButton: UIButton! {
didSet {
myButton.layer.cornerRadius = 20
myButton.layer.masksToBounds = true

Next time I will show you how to add shadows to your views, now there are fried calamari on my table waiting for me 🤤

Mom’s Calamari and Shrimps