@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的子類變成了這樣 Objective-C IBDesignable/IBInspectable 建一個ViewOC類,ViewOC繼承自UIView,選擇Objective-C語言,在.h裡面聲明屬性 @property (nonatomic, assign)IBInspectable CGFloat cornerRadius; @property (nonatomic, assign)IBInspectable CGFloat bwidth; @property (nonatomic, assign)IBInspectable UIColor *bcolor; 注意:IBInspectable修飾的位置。 然後再.m文件裡面,@implementation前面用IB_DESIGNABLE修飾。 IB_DESIGNABLE @implementation ViewOC 然後再set方法裡面去賦值就OK了,如下:
- (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是一樣的,如果有疑問和建議,歡迎指導和提問。