我不知道你有沒(méi)有覺(jué)得XIB和Storyboard提供操作View的屬性還是很少 膝晾,比如XIB中不支持為UITextField設(shè)置padding,不支持在XIB中UIImageView設(shè)置圓角... 而iOS8中為我們帶來(lái)了新的可能厢钧。
IBDesignable/IBInspectable
IBDesignable/IBInspectable 是IOS8為我們提供的新特性织咧,支持自定義屬性映射到XIB(運(yùn)行時(shí)機(jī)制) 下面是依UITextField舉例:
Objective-C IBDesignable/IBInspectable
自定義UITextField的子類娜搂,并將自定義的屬性用IBInspectable標(biāo)識(shí)
#import <UIKit/UIKit.h>
@interface IB_UITextField : UITextField
@property (nonatomic, assign)IBInspectable CGFloat cornerRadius;
@property (nonatomic, assign)IBInspectable CGFloat Padding;
@end
實(shí)現(xiàn)
IB_DESIGNABLE
@implementation IB_UITextField
- (void)setCornerRadius:(CGFloat)cornerRadius{
_cornerRadius = cornerRadius;
self.layer.cornerRadius = _cornerRadius;
self.layer.masksToBounds = YES;
}
-(CGRect)textRectForBounds:(CGRect)bounds {
return CGRectInset(bounds, _Padding, _Padding);
}
-(CGRect)editingRectForBounds:(CGRect)bounds {
return [self textRectForBounds:bounds];
}
@end
Swift IBDesignable/IBInspectable
import UIKit@IBDesignableclass FormTextField: UITextField {
@IBInspectable var Padding: CGFloat = 0
override func textRectForBounds(bounds: CGRect) -> CGRect {
return CGRectInset(bounds, Padding, Padding)
}
override func editingRectForBounds(bounds: CGRect) -> CGRect {
return textRectForBounds(bounds)
}
}
效果圖