UIViews are like Ogres, which are like onions – they have layers.
Source: Documentation
More accurately, UIView
has a single layer
property that can have infinite sublayers.
UIView’s have layers
Lets draw a circle.
First create a UIView
and a CAShapeLayer
:
let myView = UIView()
let myLayer = CAShapeLayer()
Layers have a path
UIBezierPath
makes drawing shapes extremely smooth, lets say in the shape of a circle:
let circlePath = UIBezierPath(
arcCenter: CGPoint(x: 100.0, y: 100.0),
radius: 100,
startAngle: 0 * CGFloat.pi / 180,
endAngle: 360 * CGFloat.pi / 180,
clockwise: true)
Great! Now we can add CAShapeLayer
as a CGPath
and spruce up our fill and stroke colors
myLayer.path = circlePath.cgPath
myLayer.strokeColor = UIColor.blue.cgColor
myLayer.fillColor = UIColor.yellow.cgColor
Last step! Add this layer to your UIView
myView.layer.addSublayer(myLayer)
Layers have attributes
strokeColor,
fillColor, opacity, lineWidth
and more!
Bonus: Layers can animate attributes
// create the animation
let opacityAnimation = CABasicAnimation(
keyPath: #keyPath(CALayer.opacity))
opacityAnimation.fromValue = 0
opacityAnimation.toValue = 1
opacityAnimation.duration = 5.0
// set the final value; add the animation
myLayer.opacity = 1
myLayer.add(opacityAnimation, forKey: #keyPath(CALayer.opacity))