问题
I have created simple view using interface builder. This view has one label. Do you know how to create init method for this class ? I wrote my own version but I am not sure that it is correct or not.
@interface AHeaderView ()
@property (nonatomic, weak) IBOutlet UILabel *descriptionLabel;
@end
@implementation AHeaderView
- (id)initWithFrame:(CGRect)frame {
self = [super initWithFrame:frame];
if (self) {
// add subview from nib file
NSArray *nibContents = [[NSBundle mainBundle] loadNibNamed:@"AHeaderView" owner:nil options:nil];
AHeaderView *plainView = [nibContents lastObject];
plainView.descriptionLabel.text = @"localised string";
[self addSubview:plainView];
}
return self;
}
-------------------------------- version 2 ---------------------------------
@interface AHeaderView ()
@property (nonatomic, weak) IBOutlet UILabel *descriptionLabel;
@end
@implementation AHeaderView
- (id)initWithCoder:(NSCoder *)aDecoder {
self = [super initWithCoder:aDecoder];
if (self) {
self.descriptionLabel.text = @"localised string"
}
return self;
}
loading in ViewController class:
NSArray *nibContents = [[NSBundle mainBundle] loadNibNamed:@"AHeaderView" owner:nil options:nil];
AHeaderView *headerView = [nibContents lastObject];
------- version 3 -------
@interface AHeaderView ()
@property (nonatomic, weak) IBOutlet UILabel *descriptionLabel;
@end
@implementation AHeaderView
- (void)awakeFromNib {
[super awakeFromNib];
self.descriptionLabel.text = @"localised string"
}
@end
回答1:
When loading a view from an XIB initWithFrame:
won't be called. Instead the method signature should be - (id)initWithCoder:(NSCoder *)decoder
.
In this case you shouldn't be loading the NIB in your unit method. Some other class should be loading the view from the NIB (like a controller class).
What you have currently results in a view with no label set which has a subview with a label (with some text).
来源:https://stackoverflow.com/questions/21123898/how-to-write-init-method-for-custom-uiview-class-with-xib-file