简体   繁体   English

如何在XIB中正确加载和显示自定义UIView?

[英]How to correctly load and show custom UIView in XIB?

Task is simple: 任务很简单:

  1. We have a XIB. 我们有XIB。
  2. We have a custom UIView class implementation. 我们有一个自定义的UIView类实现。 Without XIB. 没有XIB。
  3. We can add thanks to IB UIView element to the XIB and set its class to custom UIView class. 我们可以向XIB添加IB UIView元素,并将其类设置为自定义UIView类。
  4. We can create an outlet of our custom UIView class and connect custom UIView from XIB to it. 我们可以创建自定义UIView类的出口,并将自定义UIView从XIB连接到它。
  5. But it seems that we should do additional steps to show our custom UIView (and its elements -- labels, images, etc) when XIB is loaded. 但是看来,当加载XIB时,我们应该做一些额外的步骤来显示我们的自定义UIView(及其元素-标签,图像等)。
  6. Which steps? 哪个步骤?

UPD: The task is completed. UPD:任务已完成。 We should use initWithCoder. 我们应该使用initWithCoder。 Cite from Pizzaiola Gorgonzola : «initWithFrame is called when a UIView is created dynamically, from code. Pizzaiola Gorgonzola引用:«initWithFrame是通过代码动态创建UIView时调用的。 a view that is loaded from a .nib file is always instantiated using initWithCoder, the coder takes care of reading the settings from the .nib file». 从.nib文件加载的视图始终使用initWithCoder实例化,编码器负责从.nib文件中读取设置»。 Thanks to question Subviews not showing up in UIView class . 多亏了问题Subviews没有出现在UIView类中

如果这些元素不在nib / xib中,则可以在initWithCoder中添加/创建它们:

You may do something like this: 您可以执行以下操作:

//MYCustomView.h
@interface MYCustomView : UIView
@end

//MYCustomView.m
@implementation MYCustomView

- (void)setup {
    // Do custom stuffs here...
}

- (id)init {
    self = [super init];
    if (self) {
        [self setup];
    }
    return self;
}

- (id)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        [self setup];
    }
    return self;
}

- (id)initWithCoder:(NSCoder *)aDecoder {
    self = [super initWithCoder:aDecoder];
    if (self) {
        [self setup];
    }
    return self;
}

@end

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM