Apple loves a rounded rectangle. They even sneaked a couple of improvements into iOS 11. I saw these two tips during WWDC 2017 and then forgot about them.
Masked Corners
You are most likely familiar with the technique of setting a corner radius using the Core Animation layer of a view.
let blueView = UIView()
blueView.backgroundColor = .blue
blueView.layer.cornerRadius = 25.0
// ...view setup...
The cornerRadius
works on the background color of the layer. Here is the resulting rounded blue rectangle:
But what if I did not want to round all four corners? Well there is good news in iOS 11. There is now a maskedCorners
property for the layer. This is a CACornerMask
which has four possible values for each corner:
layerMaxXMaxYCorner
- bottom right cornerlayerMaxXMinYCorner
- top right cornerlayerMinXMaxYCorner
- bottom left cornerlayerMinXMinYCorner
- top left corner
Including a value results in that corner appearing rounded. It defaults to all four corners. If I wanted only the top left and bottom right corners rounded:
if #available(iOS 11, *) {
blueView.layer.maskedCorners = [.layerMinXMinYCorner, .layerMaxXMaxYCorner]
}
Which gives me this work of art:
CornerRadius Now Animatable
More good news for lovers of rounded rectangles. Starting in iOS 11 the cornerRadius
property is now an animatable property so you can do this with a standard UIView
animation block:
if #available(iOS 11, *) {
UIView.animate(withDuration: duration, animations: {
self.blueView.layer.cornerRadius = radius
}, completion: { _ in
UIView.animate(withDuration: duration, animations: {
self.blueView.layer.cornerRadius = 0
})
})
}
The result of combining masked corners with an animating corner radius: