A CAShapeLayer is added as a sublayer of a view in a certain position:
// Use Bezier Path to create a rectangle shape
let barRect = CGRect(x: 0, y: 0, width: 10, height: 100)
let barPath = UIBezierPath(rect: barRect)
let bar = CAShapeLayer()
bar.path = barPath.cgPath
bar.lineWidth = 0.5
// Place anchor on lower left corner of the rectangle
bar.anchorPoint = CGPoint(x: 0, y: 1)
bar.bounds = CGRect(origin: CGPoint.zero, size: barRect.size)
// Position bar in view
bar.position = CGPoint(x: 0, y: 200)
layer.addSublayer(bar)
Later on, an action attempts to increase the height of the rectangle:
bar.bounds.size.height = 150
When this action is executed, the rectangle changes it's position in the view, but not it's height. The top of the rectangle moves to where the rectangle should be if the height is increased, but the bottom of the rectangle also moves up, maintaining the original height of the rectangle. What is the problem here? Thanks
Changing the layer's bounds does not change the layer's
.path.If your goal is simple rectangles, you can use
CALayerinstead ofCAShapeLayerwith a path.Here's a quick example:
and a sample controller:
Tapping the yellow "BarView" will toggle the bar bounds heights between 100 and 150 ... Red bar is your original
CAShapeLayerand Cyan bar is aCALayer:Edit
Here's that same
BarViewclass, but with a 3rd (green) bar. It uses aCAShapeLayerand updates its.pathinlayoutSubviews():I changed the path for "bar3" to a
roundedRectso we can see why we might want to use aCAShapeLayer.