前綴IB,平時我們見到最多的就是可視化編程中的IBAction 和 IBOutlet 。顧名思義,IBDesignable 和 IBInspectable 也是在可視化編程中使用。
用IBInspectable聲明的屬性,可在Xcode面板裏的Runtime Attributes裏直接配置。用IBDesignable表明的控件,則可以直接在storyboard/xib中看到修改上述屬性產生的變化,不需要Run整個app。
1. 創建一個View,聲明屬性,一定要寫set方法,不然不起作用。
@IBDesignable
class TYView: UIView {
@IBInspectable var cornerRadius: CGFloat {
get { return layer.cornerRadius }
set {
layer.cornerRadius = newValue
layer.masksToBounds = newValue > 0
}
}
@IBInspectable var borderWidth: CGFloat {
get { return layer.borderWidth }
set { layer.borderWidth = newValue > 0 ? newValue : 0 }
}
@IBInspectable var borderColor: UIColor {
get { return UIColor(cgColor: layer.borderColor!) }
set { layer.borderColor = newValue.cgColor }
}
@IBInspectable var height: CGFloat {
get { return bounds.size.height }
set { bounds.size.height = newValue }
}
}
@interface TYView : UIView
@property (nonatomic, assign) IBInspectable CGFloat connerRadius;
@property (nonatomic, assign) IBInspectable CGFloat borderWidth;
@property (nonatomic, strong) IBInspectable UIColor *borderColor;
@property (nonatomic, assign) IBInspectable CGFloat height;
@end
IB_DESIGNABLE
@implementation TYView
- (void)setConnerRadius:(CGFloat)connerRadius {
_connerRadius = connerRadius;
self.layer.cornerRadius = _connerRadius;
self.layer.masksToBounds = YES;
}
- (void)setBorderWidth:(CGFloat)borderWidth {
_borderWidth = borderWidth;
self.layer.borderWidth = _borderWidth;
}
- (void)setBorderColor:(UIColor *)borderColor {
_borderColor = borderColor;
self.layer.borderColor = _borderColor.CGColor;
}
- (void)setHeight:(CGFloat)height {
_height = height;
CGRect temp = self.frame;
temp.size.height = _height;
self.frame = temp;
}
@end
2. 在storyboard拖一個view,Class選爲自定義的類,點擊面板上Runtime Attributes,會發現在類中聲明的屬性。直接修改值,storyboard上的view會直接刷新UI。
當設置完屬性值後,切換到Indentity Inspector,會出現如下圖紅框內的attributes
有一點值得注意的是,若聲明的屬性本身自帶也就是可以用點語法點出來的,比如backgroundColor。
若自定義屬性名與自帶屬性名相同,則需要 override強制重寫set方法,Runtime Attributes也會出現該屬性,但是馬上就會出現一個錯誤,並且storyboard頁面已無法正常顯示。編譯的時候是success的,然而運行時就會直接crash。
@IBInspectable override var backgroundColor: UIColor? {
get { return self.backgroundColor }
set { self.backgroundColor = newValue }
}
若自定義屬性名與自帶屬性名不相同,但是set方法賦予自帶屬性的值。則xcode面板上會出現兩處設置背景色的地方,同時設置兩個顏色最後運行出來的則以自定義屬性的值爲準。
@IBInspectable var backColor: UIColor? {
get { return self.backgroundColor }
set { self.backgroundColor = newValue }
}
最後,swift一般用的都是類型推斷, 不會直接註明屬性的類型,所以有時可能會不起作用。只要加上類型標識聲明類型後, 就能夠在xib或者sb正常使用了。