ios - 使用 IB 从 View Controller 的 View 加载带有 XIB 的自定义 UIView

标签 ios uiview xib nib initwithcoder

我有一个使用 Interface Builder 构建的自定义 UIView (MyCustomUIView)。我想把这个自定义 View 放在 MyViewController 的 View 中,它也是使用 IB 设计的。我在 MyViewController 的 XIB 中放置了一个 UIView 作为 subview ,并将其类设置为 MyCustomUIView。问题是,当我运行代码时,只出现一个空白 View 。 (当我在代码中实例化 MyCustomUIView 时,它显示得很好。)

我只是在 MyCustomUIView.m 中按以下方式覆盖 initWithFrame: 方法:

- (id)initWithFrame:(CGRect)frame
{
    [[NSBundle mainBundle] loadNibNamed:@"MyCustomUIView" owner:self options:nil];
    self = self.view;
    return self;
}

我应该怎么做才能正确加载 View ? initWithCoder: 应该是什么样子?

最佳答案

你是对的。 IB 使用 initWithCoder。 initWithCoder 应该看起来与您的其他 init 方法非常相似:

- (id)initWithCoder:(NSCoder *)aDecoder {
    self = [super initWithCoder:aDecoder];
    if (self) {
        // CUSTOM INITIALIZATION HERE
    }
    return self;
}

一旦你在 IB 中分配了你的类,你就不需要从包中实例化它,除非我误解了你的意图。

关于ios - 使用 IB 从 View Controller 的 View 加载带有 XIB 的自定义 UIView,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13199839/

相关文章:

ios - Swift 中的 ENSwiftSideMenu 阴影

ios - UIView 约束 TextView contentSize Bug

ios - 使 GridLayout 中的 NativeScript ScrollView 和 TextView 一起工作(仅限 iOS)

ios - 错误 ITMS-9000 : "Missing Code Signing Entitlements. No entitlements found in bundle" - How to change app ID name

ios - 难以本地化 xib 文件

uiview - iOS 的 slider View

swift - 保存条形图 View 时不显示条形图

iOS 昏暗背景 查看全屏

ios - 以编程方式根据 subview (标签)创建具有大小的 UIView

ios - 从 XIB 文件实例化 UIView 并将其自身作为文件的所有者?