ios - 修改 UIObject 的基类与修改 CALayer 有什么区别?

标签 ios swift

所以我一直在摆弄 UI 元素,发现很多事情都需要使用 UIElement.layer 来为 UIElement 本身的元素设置样式,即使它们都有很多相似的属性。使用

有什么区别
let button = UIButton()
button.backgroundColor(color)

结束

let button = UIButton()
button.layer.backgroundColor(color)

或者可以在 UI 元素上设置的任何其他属性?

最佳答案

两者都是设置backed layer的背景色,设置UIViewbackgroundColor属性会调用CALayer setBackgroundColor:(CGColorRef)backgroundColor final方法。

这里有一些提示,UIView的setBackgroundColor:的调用栈,可以看到调用了KDLayer的(KDLayer是CALayer的子类)的setBackgroundColor方法。

enter image description here

这是代码,它是 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/

相关文章:

ios - 在调用 resignFirstResponder 之前,UITextField 不会自动调整宽度以适应内容?

ios - 将 UITextField 输入文本翻译成西类牙语运行时

ios - CloudKit iOS 10 错误 : Account doesn't have access to CloudKit account

ios - 如何在 Swift 中以编程方式创建 SplitViewController?

ios - 应用程序启动动画仅在从 Xcode 运行时有效

iphone - 当我释放 View 时委托(delegate)崩溃,因为没有找到

ios - 按下按钮时无法使用 Swift 3 更新 SKLabel 节点

ios - 将核心数据对象附加到数组中

swift - 向右动画 UIScrollView

iOS 如何在应用程序未运行时处理 FCM