它不会为多个视图控制器重用相同的 xib。如果您想重用该视图,请创建一个继承自 UIView 的类并在其中添加代码。
#import "SomeProtocol.h"
@interface MyCustomView : UIView {
IBOutlet UIView *headerView;
IBOutlet UIView *footerView;
IBOutlet UIButton *updateBtn;
}
@property (nonatomic, assign) id<SomeProtocol> delegate;
@end
............
@implementation BCFirmwareView
@synthesize delegate = _delegate;
+ (id)viewFromNibWithName: (NSString*)name {
UIView *view = nil;
NSArray *views = [[NSBundle mainBundle] loadNibNamed: name owner: self options: nil];
if (views) {
for (UIView *aView in views) {
if ([aView isKindOfClass: NSClassFromString(name)])
view = aView;
}
}
return view;
}
- (id)initWithCoder:(NSCoder *)aDecoder {
self = [super initWithCoder: aDecoder];
if (self) {
}
return self;
}
- (id)init {
self = [[MyCustomView viewFromNibWithName: @"MyCustomView"] retain];
if (self) {
}
return self;
}
- (void)dealloc {
self.delegate = nil;
[headerView release];
[footerView release];
[updateBtn release];
[super dealloc];
}
- (void)awakeFromNib {
[super awakeFromNib];
// Do any additional setup after loading the view from its nib.
headerView.backgroundColor = [UIColor redColor];
footerView.backgroundColor = [UIColor greenColor];
}
- (void)willMoveToSuperview:(UIView *)newSuperview {
[super willMoveToSuperview: newSuperview];
if (!newSuperview)
return;
}
- (void)didMoveToSuperview {
[super didMoveToSuperview];
}
- (IBAction)updateBtnPressed: (id)sender {
// do some stuff
}
@end
下一步是在 Interface Builder 中打开 xib 并将您的类设置为视图的自定义类,而不是文件的响应程序。右键单击视图并建立插座和操作连接。
现在您应该能够在任何视图控制器中简单地创建 MyCustomView 的实例并使用它。如果您没有忘记将视图自定义类更改为您的类,则也可以在 Interface Builder 中使用。