iOS8新特性IBDesignable/IBInspectable,能夠直接在XIB或者Storyboard中直接,設置UI類的屬性。
例如:UIView.layer.borderWidth、borderColor、cornerRadius這些屬性在XIB上是不能直接設置的,可是IBDesignable/IBInspectable,利用運行時機制,就能夠把這些屬性映射到XIB上了,同時咱們UI類的自定義屬性也能夠映射上去。關於過多的解釋我就很少說了能夠看看Nate Cook撰寫的。bash
首先咱們得建一個ViewSwift類,View繼承自UIView,選擇Swift語言。atom
@IBDesignable class View: UIView { @IBInspectable var cornerRadius: CGFloat = 0.0 { didSet { layer.cornerRadius = cornerRadius layer.masksToBounds = true } } @IBInspectable var borderColor: UIColor = UIColor() { didSet { layer.borderColor = borderColor.CGColor } } @IBInspectable var borderWidth: CGFloat = 0.0 { didSet { layer.borderWidth = borderWidth } } }
而後在XIB或Storyboard裏面,拖一個UIView上去,把class改爲本身定義的View
而後點擊旁邊的屬性編輯,就能夠看到咱們動態加載上去的屬性,直接修改就能夠了,XIB上的View也會跟隨變化。
咱們就能夠看到一個UIView的子類變成了這樣
spa
建一個ViewOC類,ViewOC繼承自UIView,選擇Objective-C語言,在.h裏面聲明屬性3d
@property (nonatomic, assign)IBInspectable CGFloat cornerRadius; @property (nonatomic, assign)IBInspectable CGFloat bwidth; @property (nonatomic, assign)IBInspectable UIColor *bcolor;
注意:IBInspectable修飾的位置。code
而後再.m文件裏面,@implementation前面用IB_DESIGNABLE修飾。繼承
IB_DESIGNABLE @implementation ViewOC
而後再set方法裏面去賦值就OK了,以下:token
- (void)setCornerRadius:(CGFloat)cornerRadius{ _cornerRadius = cornerRadius; self.layer.cornerRadius = _cornerRadius; self.layer.masksToBounds = YES; } - (void)setBcolor:(UIColor *)bcolor{ _bcolor = bcolor; self.layer.borderColor = _bcolor.CGColor; } - (void)setBwidth:(CGFloat)bwidth { _bwidth = bwidth; self.layer.borderWidth = _bwidth; }
效果跟上面Swift是同樣的,若是有疑問和建議,歡迎指導和提問。ip