I want to subclass UIView in swift, and use a CAShapeLayer is the layer type for this subclass - overriding the layer type with layerClass().
How do I access properties that are in CAShapeLayer, but not in CALayer - such as path in the example below. The code below does not compile because path is not a member of CALayer.
override class func layerClass() -> AnyClass {
return CAShapeLayer.self
}
override func awakeFromNib() {
var path: UIBezierPath = UIBezierPath.init(ovalInRect: CGRectMake(0, 0, 30, 10))
self.layer.path = path.CGPath
}
Note that self.layer always returns a generic CALayer inside a UIView, so you have to typecast it to your specific class to make sure that it has the correct type. You can do the following to make sure that you call path to CAShapeLayer not to CALayer class type.
override class func layerClass() -> AnyClass {
return CAShapeLayer.self
}
override func awakeFromNib() {
guard let shapeLayer = self.layer as? CAShapeLayer else { return }
let path: UIBezierPath = UIBezierPath.init(ovalInRect: CGRectMake(0, 0, 30, 10))
shapeLayer.path = path.CGPath
}
It seems that as of Swift 3 the answer is
override public class var layerClass: Swift.AnyClass {
get {
return CAShapeLayer.self
}
}
Cast the layer and then use path property
(self.layer as! CAShapeLayer).path = path.CGPath
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With