Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does CABasicAnimation try to initialize another instance of my custom CALayer?

Tags:

swift

I get this error:

fatal error: use of unimplemented initializer 'init(layer:)' for class 'MyProject.AccordionLayer'

using the following code. In my view controller:

override func viewDidLoad() {
    let view = self.view as! AccordionView!
    view.launchInitializationAnimations()
}

In my view:

required init(coder aDecoder: NSCoder) {
    super.init(coder: aDecoder)

    for var i = 0; i < self.accordions.count; ++i {
        var layer = AccordionLayer(accordion: self.accordions[i])
        layer.accordion = self.accordions[i]
        layer.frame = CGRectMake(0, CGFloat(i) * self.getDefaultHeight(), self.frame.width, self.getDefaultHeight())
        self.layer.addSublayer(layer)
        layer.setNeedsDisplay()
        layers.append(layer)
    }
}

func launchInitializationAnimations() {
    for layer in self.layer.sublayers {
        var animation = CABasicAnimation(keyPath: "topX")
        animation.duration = 2.0
        animation.fromValue = CGFloat(0.0)
        animation.toValue = CGFloat(200.0)
        layer.addAnimation(animation, forKey: "animateTopX")
    }
}

And in my subclassed CALayer

var topX : Int
init(accordion: (color: CGColorRef!, header: String, subtitle: String, image: UIImage?)!) {

    // Some initializations
    // ...

    super.init()
}

I also implement needsDisplayForKey, drawInContext.

I have seen 2-3 other questions with the same error message but I can't really figure out how it is related to my specific case on my own.

Why is CABasicAnimation trying to instantiate a new (my custom) CALayer?

like image 445
Tobias Avatar asked Aug 08 '15 12:08

Tobias


2 Answers

I just ran into the same issue, and I got it working after adding the init(layer:) to my custom CALayer:

override init(layer: Any) {
    super.init(layer: layer)
}

I hope it helps whoever get here.


EDIT As Ben Morrow comments, in your override you also have to copy across the property values from your custom class. For an example, see his https://stackoverflow.com/a/38468678/341994.

like image 65
gfpacheco Avatar answered Sep 24 '22 05:09

gfpacheco


Why is CABasicAnimation trying to instantiate a new (my custom) CALayer?

Because animation involves making a copy of your layer to act as the presentation layer.

like image 42
matt Avatar answered Sep 25 '22 05:09

matt