Don Wilson
Don Wilson

Reputation: 2303

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
}

Upvotes: 6

Views: 5000

Answers (4)

Robin Stewart
Robin Stewart

Reputation: 3883

Even more concise, from the documentation (Swift 4):

override class var layerClass: AnyClass {
    return CAShapeLayer.self
}

Upvotes: 2

Guig
Guig

Reputation: 10187

It seems that as of Swift 3 the answer is

override public class var layerClass: Swift.AnyClass {
    get {
        return CAShapeLayer.self
    }
}

Upvotes: 8

Ch0k0l8
Ch0k0l8

Reputation: 837

Cast the layer and then use path property

 (self.layer as! CAShapeLayer).path = path.CGPath

Upvotes: 2

Sandeep
Sandeep

Reputation: 21144

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
    }

Upvotes: 8

Related Questions