我使用界面生成器创建了简单的 View 。此 View 有一个标签。你知道如何为这个类创建 init 方法吗?我写了我自己的版本,但我不确定它是否正确。
@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;
}
--------------------------------版本 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;
}
在 ViewController 类中加载:
NSArray *nibContents = [[NSBundle mainBundle] loadNibNamed:@"AHeaderView" owner:nil options:nil];
AHeaderView *headerView = [nibContents lastObject];
-------- 版本 3 --------
@interface AHeaderView ()
@property (nonatomic, weak) IBOutlet UILabel *descriptionLabel;
@end
@implementation AHeaderView
- (void)awakeFromNib {
[super awakeFromNib];
self.descriptionLabel.text = @"localised string"
}
@end
最佳答案
从 XIB 加载 View 时 initWithFrame:
不会被调用。相反,方法签名应该是 - (id)initWithCoder:(NSCoder *)decoder
。
在这种情况下,您不应在单元方法中加载 NIB。其他一些类应该从 NIB 加载 View (如 Controller 类)。
您当前的结果是没有标签集的 View ,该 View 有一个带有标签(带有一些文本)的 subview 。
关于ios - 如何使用 xib 文件为自定义 UIView 类编写 init 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21123898/