Today we're going to talk about corners. Specifically, rounded ones. In iOS 11, Apple has improved the way we can specify and work with the rounding of our views' corners. Let's take a look.
Let's begin with where we were before iOS 11.
Before iOS 11, configuring a UIView
to have round corners went like this:
let view = UIView()
view.clipsToBounds = true
view.layer.cornerRadius = 8
The clipsToBounds
ensures the "clipping" takes place, and the next rounds all four corners with a radius of 8
:
Pretty straightforward.
This approach works great for rounding all four corners of a view. But what if we wanted to round only some of the four corners? Previously we'd need to drop down and create our own mask layer, giving it a path we created manually. Bummer.
iOS 11 makes this way easier.
Meet CACornerMask
!
Now, we can use the same code as before, with one small addition:
let view = UIView()
view.clipsToBounds = true
view.layer.cornerRadius = 8
view.layer.maskedCorners = [.layerMaxXMaxYCorner, .layerMinXMaxYCorner]
Now we can use the new CACornerMask option set to specify which corners we'd like rounded. Here we've asked for just the bottom two corners to be rounded with an 8
point radius:
Neat!
Before we go, there's one last thing to know about round corners in iOS 11:
They are now completely animatable! 🎉
In previous releases, this next bit of code wouldn't do anything, but in iOS 11 this works exactly as expected:
let view = UIView()
view.clipsToBounds = true
view.layer.cornerRadius = 16
UIViewPropertyAnimator(duration: 1, curve: .linear) {
view.layer.cornerRadius = 0
}.startAnimation()
Very cool.