通過IB設(shè)置View屬性的時候有一些局限性池磁,往往有一些屬性沒有暴露在IB的設(shè)置面板中,這時候我們需要通過設(shè)置@IBOutlet
,或者在IB上使用User Defined Runtime Attributes
通過KVC的方式配置一些你在IB 中不能配置的屬性,這樣增加了大量的開發(fā)時間。
在工程實(shí)踐中优烧,在對應(yīng)的view中添加IBInspectable
的方式來解決對IB或者SB的使用,帶來實(shí)質(zhì)性的改善
1.通過自定義對應(yīng)view的方式链峭,動態(tài)在IB上顯示修改的內(nèi)容
.h
// 在`@interface`前畦娄,加上`IB_DESIGNABLE`實(shí)現(xiàn)IB上的動態(tài)布局
IB_DESIGNABLE
@interface customLabel : UILabel
// 在聲明屬性類型前,加上`IBInspectable`,在IB上顯示成員屬性
@property (nonatomic,assign) IBInspectable CGFloat cornerRadius;
@property (nonatomic,assign) IBInspectable CGFloat borderWidth;
@property (nonatomic,strong) IBInspectable UIColor *borderColor;
@end
.m
/**
重寫set、get方法實(shí)現(xiàn)需要的內(nèi)容
*/
@implementation customLabel
- (void)setCornerRadius:(CGFloat)cornerRadius {
self.layer.cornerRadius = cornerRadius;
self.clipsToBounds = cornerRadius > 0;
}
- (CGFloat)cornerRadius {
return self.layer.cornerRadius;
}
- (void)setBorderWidth:(CGFloat)borderWidth {
self.layer.borderWidth = borderWidth;
}
- (CGFloat)borderWidth {
return self.layer.borderWidth;
}
- (void)setBorderColor:(UIColor *)borderColor {
self.layer.borderColor = borderColor.CGColor;
}
- (UIColor *)borderColor {
return [UIColor colorWithCGColor:self.layer.borderColor];
}
@end
import UIKit
@IBDesignable
class cuntomLabel: UILabel {
@IBInspectable var cornerRadius : CGFloat {
get {
return layer.cornerRadius
}
set {
layer.cornerRadius = newValue
clipsToBounds = newValue > 0
}
}
}
優(yōu)點(diǎn):可以在IB或者SB上可以直觀的顯示修改的屬性
缺點(diǎn):IB上的view必須使用對應(yīng)的自定義的view才可以修改弊仪,耦合性太強(qiáng)
2.在對應(yīng)的view中添加IBInspectable的extension方法來解決
.h
// `IB_DESIGNABLE` 僅對自定義view有效,分類上使用無效
@interface UILabel (Extension)
@property (nonatomic,assign) IBInspectable CGFloat cornerRadius;
@property (nonatomic,assign) IBInspectable CGFloat borderWidth;
@property (nonatomic,strong) IBInspectable UIColor *borderColor;
@end
.m
@implementation UILabel (Extension)
- (void)setCornerRadius:(CGFloat)cornerRadius {
self.layer.cornerRadius = cornerRadius;
self.clipsToBounds = cornerRadius > 0;
}
- (CGFloat)cornerRadius {
return self.layer.cornerRadius;
}
- (void)setBorderWidth:(CGFloat)borderWidth {
self.layer.borderWidth = borderWidth;
}
- (CGFloat)borderWidth {
return self.layer.borderWidth;
}
- (void)setBorderColor:(UIColor *)borderColor {
self.layer.borderColor = borderColor.CGColor;
}
- (UIColor *)borderColor {
return [UIColor colorWithCGColor:self.layer.borderColor];
}
@end
import UIKit
extension UILabel {
@IBInspectable var cornerRadius : CGFloat {
get {
return layer.cornerRadius
}
set {
layer.cornerRadius = newValue
clipsToBounds = newValue > 0
}
}
}
優(yōu)點(diǎn):不需要自定義view,可直接在IB上對顯示定義的屬性進(jìn)行修改熙卡,無耦合性
缺點(diǎn):和使用User Defined Runtime Attributes
一樣,不能直觀的顯示修改的屬性励饵,需要運(yùn)行程序才能顯示效果
3.使用IBInspectable
系統(tǒng)會自動在User Defined Runtime Attributes
添加使用的屬性,若果不想使用在IB上自定義的屬性驳癌,一定要清空User Defined Runtime Attributes
內(nèi)的值
最后編輯于 :2017.12.08 07:12:21
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者