iOS自定义xib属性

XIB和Storyboard提供操作View的属性还是很少,例如XIB中不支持view设置圆角(Key Path非可视化),而iOS8中为我们带来了新的可能。

Objective-C IBDesignable/IBInspectable

1
2
3
4
#import <UIKit/UIKit.h>
@interface IB_UIView : UIView
@property (nonatomic, assign)IBInspectable CGFloat cornerRadius;
@end
1
2
3
4
5
6
7
8
9
IB_DESIGNABLE
@implementation IB_UIView

- (void)setCornerRadius:(CGFloat)cornerRadius {
_cornerRadius = cornerRadius;
self.layer.cornerRadius = _cornerRadius;
self.layer.masksToBounds = YES;
}
@end

Swift IBDesignable/IBInspectable

1
2
3
4
5
import UIKit
@IBDesignable class IB_UIView: UIView {

@IBInspectable var cornerRadius: CGFloat
}

效果如下:

LM