This is an example from a book I read: iOS Core Animation: Advanced Techniques
The example in the book was written in Objective-C, which I would convert it into Swift Language as my learning reference. The goal of this example is to create a subclass of UIView, and overrides the layerClass class method to return different layer subclass at creation time. UIView calls the class method layerClass during its initiation, and uses the class it returns to create its backing layer.
In this example, a UILabel subclass called LayerLabel that draws its text using a CATextLayer instead of using the slower method drawRect approach that UILabel uses.
Some notes I marked down when converting from objective-c to swift:
1. NSObject class method is removed in Swift.
In objective-C example:
+(Class) layerClass {
return [CATextLayer class];
}
Instead, in Swift, we can simply return CATextLayer.self as class
override class func layerClass() -> AnyClass {return CATextLayer.self}
2. UIView initiation method now is called init() in Swift rather than initWithFrame: in Objective-C
In objective-C:
-(id) initWithFrame: (CGRect) frame {
if (self = [super initWithFrame: frame]) {
[self setup];
}
return self;
}
In Swift:
required init(coder aDecoder: NSCoder) {
super.init(coder:aDecoder)
self.setup()
}override init(frame:CGRect) {
super.init(frame:frame)self.setup()}
override func awakeFromNib() {
super.awakeFromNib()
self.setup()}
Here is the example rewritten in Swift: