Part 1: Elevation
Within the standard Apple elements I believe they attempt to blur things that are at a lower level in the UI. For Material Design its all about elevation and shadows.
To add the shadow we can use the CALayer class like so.
self.layer.maskToBounds = false
self.layer.shadowColor = Color().black.CGColor
self.layer.shadowOffset = CGSize(width: 0, height: elevation)
self.layer.shadowOpacity = 0.24
self.layer.shadowRadius = CGFloat(elevation)
To find the correct elevation for each view see the the docs. Since we are going to be using this code for multiple cases lets make a protocol.
protocol MaterialView {
func elevate(elevation: Double)
}
No we need to make UIView conform the to protocol. We can do that like so.
extension UIView: MaterialView { func elevate(elevation: Double) { self.layer.masksToBounds = false self.layer.shadowColor = Color().black.CGColor self.layer.shadowOffset = CGSize(width: 0, height: elevation) self.layer.shadowRadius = CGFloat(elevation) self.layer.shadowOpacity = 0.24 }}
But wait, what if I need the shadow to be above the view instead of below it, i.e. a bottom navigation bar. Ok lets add a simple if then check to make sure we pass the right value to the layer. First take out
self.layer.shadowRadius = CGFloat(elevation)
We will replace it with.
if elevation >= 0.0 { self.layer.shadowRadius = CGFloat(elevation)} else { self.layer.shadowRadius = -CGFloat(elevation)}
But, wait we can do better, now replace that code with.
self.layer.shadowRadius = abs(CGFloat(elevation))
Now for all our views we can just use.
self.elevate(2.0)
Or whatever elevation the docs say to use. That covers elevating the views the way Material Design states.
Next up: Color