Clicky

iOS Dev Nugget 135 CAShapeLayer, Animated Views and XCPShowView()

.

Need to run a code review on your codebase? Hire me

It's easy to forget that UIViews are backed by CALayers and the interesting things you can do with CALayers and CALayer subclasses. One of those — CAShapeLayer — lets you draw Bezier splines. So you essentially create a UIBezierPath instance and assign it to the CAShapeLayer instance, configuring how you want it to be displayed, such as fillColor, and strokeColor. For e.g. the following playground code will draw a square with a dotted outline and animate drawing the outline:

import UIKit
import XCPlayground
XCPSetExecutionShouldContinueIndefinitely()

var path = UIBezierPath(rect: CGRectMake(50, 50, 100, 100))

var layer = CAShapeLayer()
layer.path = path.CGPath
layer.fillColor = UIColor.clearColor().CGColor
layer.strokeColor = UIColor.blueColor().CGColor
layer.lineWidth = 2
layer.lineDashPattern = [10, 3]

var animation = CABasicAnimation(keyPath: "strokeEnd")
animation.duration = 3
animation.fromValue = 0
animation.toValue = 1
layer.addAnimation(animation, forKey:"whatever")
layer.strokeEnd = 1

var v = UIView(frame: CGRectMake(0, 0, 200, 200))
v.backgroundColor = .whiteColor()
v.layer.addSublayer(layer)
XCPShowView("layer animating", v)

There's an issue though. If you paste the code into a Playground, you'll notice that the square doesn't animate. You might also see this error:

MyPlayground[98066:1375145] Error sending deferral props: 0x10000003

Notice the use of XCPSetExecutionShouldContinueIndefinitely(). In addition to that, you'll have to enable Run in Full Simulator in the Playground's inspector (View > Utilities > Show File Inspector). This is mentioned in Xcode's release notes. Once you do that, re-run the playground and it should work.

Also note the use of XCPShowView() which displays the view live. If you only inspect the value of v, you will only see a snapshot and hence not see the animation.


Your feedback is valuable: Do you want more nuggets like this?   Yes   or   No

.

.

Like this and want such iOS dev nuggets to be emailed to you, weekly?

Sign Me Up! or follow @iosdevnuggets on Twitter

.

View archives of past issues