2016-08-10 10 views
3

私はUI要素を手にしていましたが、UIElement.layerを使用してUIElement自体の上に要素をスタイルするためには、多くの要素が同じような多くのプロパティを持っています。UIObjectのベースとCALayerの違いは何ですか?

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

やUI要素に設定することができる他の任意のプロパティを超える

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

を使用しての違いは何でしょうか?

答えて

1

それらの両方裏打ちされた層の背景色を設定するには、UIViewbackgroundColorプロパティは、最終的にCALayersetBackgroundColor:(CGColorRef)backgroundColorメソッドを呼び出します設定しました。

ここにいくつかのヒント、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]; 
1

彼らはUIButtonのbackgroundColorプロパティのセッターとゲッターは、ちょうどビューのレイヤーのプロパティを操作する

var b:UIButton = UIButton(frame: CGRect(x: 0, y: 0, width: 100, height: 20)) 
b.setTitle("Normal", for: UIControlState(rawValue: UInt(0))) 
b.backgroundColor = UIColor(colorLiteralRed: 1.0, green: 0.0, blue: 0.0, alpha: 1.0) 
b.layer.backgroundColor == b.backgroundColor?.cgColor // returns "true" 

(ビューのbackgroundColorのはUIColorあり、かつ層のCGColorである)タイプを除いて、実際には同じです。ドキュメンテーションによると、UIViewのbackgroundColorプロパティはiOS 2.0で追加されています。その前に、レイヤーを操作するだけでそれを変更することができました。

関連する問題