Don Wilson Don Wilson - 3 months ago 14
Swift Question

Overriding default layer type in UIView in swift

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
}

Answer

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
    }
Comments