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?
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With