How do you override UIView's +(id)layer; class

2019-03-22 08:45发布

I read in the documentation that a UIView's 'layer' property is read only and that you must override UIView's

+ (id)layer;

class method to access the layer's styling properties.

Are there any examples of overriding this method to return a layer/view with styling properties already applied?

1条回答
成全新的幸福
2楼-- · 2019-03-22 08:58

If you just want to set properties like backgroundColor, opacity, etc. on the default CALayer that's assigned to the UIView, you can set those on the UIView's layer at any time using something like the following:

view.layer.opacity = 0.0f;

The only time that you would need to override the - (CALayer)layer method would be if you wanted to return a custom CALayer subclass. I believe that on the iPhone Apple recommends you override the class method layerClass instead. This will return the CALayer subclass to be created when initializing your custom view. For example,

+ (Class) layerClass 
{
    return [CAEAGLLayer class];
}

causes your UIView subclass to use an OpenGL layer for its backing.

查看更多
登录 后发表回答