如何使用xib文件为自定义UIView类编写init方法 [英] How to write init method for custom UIView class with xib file
问题描述
我使用界面构建器创建了简单的视图.此视图有一个标签.你知道如何为这个类创建 init 方法吗?我写了自己的版本,但我不确定它是否正确.
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;
}
-------------------------------- 版本 2 ---------------------------------
-------------------------------- 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;
}
在 ViewController 类中加载:
loading in ViewController class:
NSArray *nibContents = [[NSBundle mainBundle] loadNibNamed:@"AHeaderView" owner:nil options:nil];
AHeaderView *headerView = [nibContents lastObject];
------- 版本 3 -------
------- version 3 -------
@interface AHeaderView ()
@property (nonatomic, weak) IBOutlet UILabel *descriptionLabel;
@end
@implementation AHeaderView
- (void)awakeFromNib {
[super awakeFromNib];
self.descriptionLabel.text = @"localised string"
}
@end
推荐答案
从 XIB 加载视图时 initWithFrame:
不会被调用.相反,方法签名应该是 - (id)initWithCoder:(NSCoder *)decoder
.
When loading a view from an XIB initWithFrame:
won't be called. Instead the method signature should be - (id)initWithCoder:(NSCoder *)decoder
.
在这种情况下,您不应在单元方法中加载 NIB.其他一些类应该从 NIB 加载视图(如控制器类).
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).
这篇关于如何使用xib文件为自定义UIView类编写init方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!