我有许多用笔尖设计的可重用视图,它们都是 NibView 类的子类
class NibView: UIView {
var view: UIView!
func setupNib(nibName:String) {
view = loadViewFromNib(nibName)
view.frame = bounds
view.autoresizingMask = UIViewAutoresizing.FlexibleWidth | UIViewAutoresizing.FlexibleHeight
addSubview(view)
}
func loadViewFromNib(nibName:String) -> UIView {
let bundle = NSBundle(forClass: self.dynamicType)
let nib = UINib(nibName: nibName, bundle: bundle)
let view = nib.instantiateWithOwner(self, options: nil)[0] as! UIView
return view
}
}
我像这样子类化
@IBDesignable class ExampleView: NibView {
@IBOutlet weak var label: UILabel!
private var _property:Int = 0
@IBInspectable var property:Int {
set {
_property = newValue
label.text = "\(newValue)"
} get {
return _property
}
}
override init(frame: CGRect) {
super.init(frame: frame)
setup()
}
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setup()
}
func setup() {
setupNib("ExampleView")
}
override func layoutSubviews() {
super.layoutSubviews()
// custom init
}
}
在 NIB 文件中,我将文件的所有者设置为 ExampleView。一切都完美无缺,故事板和 xib 都可以实时呈现一切。
现在,在 Objective-C 中做同样的事情是行不通的
IB_DESIGNABLE
@interface ExampleView : NibView
@property (nonatomic) IBInspectable NSUInteger count;
@end
@implementation NibView
- (void)setupNib:(NSString *)nibName {
self.view = [self loadViewFromNib:nibName];
self.view.frame = self.bounds;
self.view.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
[self addSubview:self.view];
}
- (UIView *)loadViewFromNib:(NSString *)nibName {
UIView *view = [[[NSBundle mainBundle] loadNibNamed:nibName owner:self options:nil] objectAtIndex:0];
return view;
}
@end
和
@implementation ExampleView
- (id)init {
self = [super init];
if(self) {
[self setup];
}
return self;
}
- (id)initWithFrame:(CGRect)frame {
self = [super initWithFrame:frame];
if(self) {
[self setup];
}
return self;
}
- (id)initWithCoder:(NSCoder *)aDecoder {
self = [super initWithCoder:aDecoder];
if(self) {
[self setup];
}
return self;
}
- (void)setup {
[self setupNib:@"ExampleView"];
// Custom init
}
任何想法?