【问题标题】:How to write init method for custom UIView class with xib file如何使用 xib 文件为自定义 UIView 类编写 init 方法
【发布时间】:2014-02-03 02:58:08
【问题描述】:

我使用界面生成器创建了简单的视图。此视图有一个标签。你知道如何为这个类创建 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

【问题讨论】:

    标签: ios objective-c uiview xib


    【解决方案1】:

    当从 XIB 加载视图时,initWithFrame: 不会被调用。相反,方法签名应该是- (id)initWithCoder:(NSCoder *)decoder

    在这种情况下,您不应该在单元方法中加载 NIB。其他一些类应该从 NIB 加载视图(如控制器类)。

    您当前拥有的结果是一个没有标签集的视图,它有一个带有标签的子视图(带有一些文本)。

    【讨论】:

    • 新版本可以吗?
    • 看起来好多了,是的。
    • 小问题我不能在 initWithCoder 类中写 self.descriptionLabel.text = @"localised string"。文字没有改变
    • 插座是否连接在XIB中?如果你调试它应该是可用的。
    • 我必须是一个更好的地方来更改标签的文本:stackoverflow.com/questions/11926862/…
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-27
    • 1970-01-01
    • 2016-07-31
    • 2014-10-20
    • 2012-03-09
    相关资源
    最近更新 更多