所以我一直在摆弄 UI 元素,发现很多事情都需要使用 UIElement.layer 来为 UIElement 本身的元素设置样式,即使它们都有很多相似的属性。使用
有什么区别let button = UIButton()
button.backgroundColor(color)
结束
let button = UIButton()
button.layer.backgroundColor(color)
或者可以在 UI 元素上设置的任何其他属性?
最佳答案
两者都是设置backed layer的背景色,设置UIView
的backgroundColor
属性会调用CALayer
的 setBackgroundColor:(CGColorRef)backgroundColor
final方法。
这里有一些提示,UIView的setBackgroundColor:
的调用栈,可以看到调用了KDLayer的(KDLayer是CALayer的子类)的setBackgroundColor方法。
这是代码,它是 Objective-C 代码,但我认为它很容易理解。
KDView
子类 UIView
@implementation KDView
+ (Class)layerClass {
return [KDLayer class];
}
@end
KDLayer
子类 CALayer
@implementation KDLayer
- (void)setBackgroundColor:(CGColorRef)backgroundColor {
[super setBackgroundColor:backgroundColor];
}
@end
在 KDLayer 的 setBackgroundColor: 方法中添加一个断点并创建一个 KDView 实例并修改它的 backgroundColor
属性。
KDView *v = [KDView new];
v.backgroundColor = [UIColor redColor];
关于ios - 修改 UIObject 的基类与修改 CALayer 有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38884424/