![](/img/trans.png)
[英]How to initialize/instantiate a custom UIView class with a XIB file in Swift
[英]How to write init method for custom UIView class with xib file
我使用界面構建器創建了簡單視圖。 此視圖有一個標簽。 你知道如何為這個類創建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 initWithFrame:
加載視圖時initWithFrame:
不會被調用。 相反,方法簽名應該是- (id)initWithCoder:(NSCoder *)decoder
。
在這種情況下,您不應該在單位方法中加載NIB。 其他一些類應該從NIB加載視圖(如控制器類)。
您當前所擁有的結果是沒有標簽集的視圖,該視圖具有帶標簽的子視圖(帶有一些文本)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.