ios - 如何使用 xib 文件为自定义 UIView 类编写 init 方法

标签 ios objective-c uiview xib

我使用界面生成器创建了简单的 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/

相关文章:

ios - UITableView 滚动时改变 UIView 的高度

ios - UIScrollView 不工作

iOS:UIButton 不显示

ios - 应用程序在 iPhone 中以黑屏启动

ios - UIView 可以自动获取 UIViewController 的引用吗?

ios - 尝试插入 10000 条记录 sqlite ios swift

ios - Swift 4.1 JWT http header 承载在服务器中返回401

iPhone SDK - 大 UITableViewCell

ios - 从 Storyboard 中实例化几个可拖动的图 block - 附上测试代码和屏幕截图

iOS UIStackView 单独改变 UIViews 的间距