如何为UI控件在XIB和Storyboard添加属性
2016-01-04 本文已影响1102人
sprint
我不知道你有没有觉得XIB和Storyboard提供操作View的属性还是很少 ,比如XIB中不支持为UITextField设置padding,不支持在XIB中UIImageView设置圆角... 而iOS8中为我们带来了新的可能。
IBDesignable/IBInspectable
IBDesignable/IBInspectable 是IOS8为我们提供的新特性,支持自定义属性映射到XIB(运行时机制) 下面是依UITextField举例:
Objective-C IBDesignable/IBInspectable
自定义UITextField的子类,并将自定义的属性用IBInspectable标识
#import <UIKit/UIKit.h>
@interface IB_UITextField : UITextField
@property (nonatomic, assign)IBInspectable CGFloat cornerRadius;
@property (nonatomic, assign)IBInspectable CGFloat Padding;
@end
实现
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)
}
}
![](https://img.haomeiwen.com/i574653/6a4487d15cacec46.png)