R – How to subclass CALayer to return a pre-styled layer


How do you subclass CALayer so that you return a layer with styling properties already set?

So that:

MyCustomLayer *layer = [MyCustomLayer layer];

would create a layer with these properties;

layer.backgroundColor = sweetBackgroundColor.CGColor;
layer.borderColor = sweetBorderColor.CGColor;

layer.borderWidth = 2.0;
layer.cornerRadius = 8.0;

So that I can just set its frame and add it to the tree.

But I guess my question really could just be, how do you subclass an object so that it has properties already set at creation. Possible?

Best Solution

Just override -init (the designated initializer for CALayer) in your subclass, and set those properties in your override. Any creation method, including -layer, should end up routing through the designated initializer, meaning your extra setup will happen even for convenience constructors.