How to write init method for custom UIView class with xib file

怎甘沉沦 提交于 2019-12-07 17:13:57

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!