Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Overriding default layer type in UIView in swift

Tags:

ios

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
}
like image 364
Don Wilson Avatar asked Jul 23 '15 21:07

Don Wilson


3 Answers

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
    }
like image 96
Sandeep Avatar answered Oct 19 '22 21:10

Sandeep


It seems that as of Swift 3 the answer is

override public class var layerClass: Swift.AnyClass {
    get {
        return CAShapeLayer.self
    }
}
like image 8
Guig Avatar answered Oct 19 '22 20:10

Guig


Cast the layer and then use path property

 (self.layer as! CAShapeLayer).path = path.CGPath
like image 2
Ch0k0l8 Avatar answered Oct 19 '22 20:10

Ch0k0l8