Overriding the default layer type in a UIView in swift

I want to subclass UIView in swift, and CAShapeLayer - the layer type for this subclass - overriding the layer type with layerClass ().

How can I access properties that are in CAShapeLayer but not in CALayer - for example, in the example below. The code below does not compile because the 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
}
+4
source share
3 answers

Note that self.layer always returns a generic CALayer inside a UIView, so you must cast it to your class to make sure it is of the correct type. You can do the following to make sure that you call the path to CAShapeLayer, and not to the type of the CALayer class.

   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
    }
+4
source

Swift 3 seems to have the answer

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

, path

 (self.layer as! CAShapeLayer).path = path.CGPath
+2
source

Source: https://habr.com/ru/post/1599400/


All Articles