ios - 使用带有 Storyboard 的自定义 View 而不添加两次

标签 ios iphone objective-c

我正在使用 Storyboard 并尝试为不同的 ViewController 重用 View。

为此,我创建了一个自定义的 .xib ( MyCustomView.xib ) 和类 ( MyCustomView ),几乎无处不在。

在我的 Storyboard中,我将自定义 View 设置为 MyCustomView 类型。 .

MyCustomView.xib , 将 First Responder 设置为 MyCustomView .

MyCustomView.m ,我添加了以下方法:

-(id)initWithCoder:(NSCoder *)aDecoder{
    if ((self = [super initWithCoder:aDecoder])){
        UIView *myCustomView = [[[NSBundle mainBundle] loadNibNamed:@"MyCustomView" owner:self options:nil] objectAtIndex:0];
        [self addSubview: myCustomView];
    }
    return self;
}

问题是,[self addSubview: myCustomView]添加一个新的 MyCustomView到现有的MyCustomView ,所以 View 被添加了两次。

我怎样才能摆脱两者之一?

编辑

我的问题不是很清楚,所以我认为一些屏幕截图会有所帮助。

这是我的带有自定义 View 的 Storyboard。自定义类设置为 MyCustomView .
Storyboard with MyCustomView

(我还添加了灰色背景和仅用于测试目的的标签)

现在,在 MyCustomView.xib ,我将文件的所有者设置为 MyCustomView 类:
MyCustomView.xib

并为 title Label 和 imageView 添加 outlet:
MyCustomView.xib

使用上面编写的 initWithCoder 方法,这可以正常工作,除非我调试时可以看到:
MyCustomView.m
所以self当然是 MyCustomView 类型,在 Storyboard 中选择,但它包含 2 个 subview :
  • 首先是我的 Storyboard中的测试标签
  • 二是来自MyCustomView.xib的观点,本身包含一个标签和 ImageView 。 这就是我要摆脱的观点 .
  • 最佳答案

    什么是自我?

    在这里,它是您刚刚实例化的 MyCustomView。因此,您正在向由 initWithCoder 方法创建的新 MyCustomView 实例添加一个新的 UIView(不是 MyCustomView)。

    initWithCoder 是加载 Storyboard View 时调用的方法。

    如果你想实例化一个新的 MyCustomView 在你的 MyCustomViewController 你必须打电话

    MyCustomView *newInstance = [[MyCustomView alloc] init];
    [self addSubview:newInstance];
    

    其中 self 是 Storyboard 中 MyCustomViewController 的实例。

    编辑

    好的,我更理解你的问题。
    如果你想加载 MyCustomView nib 文件,你不需要为它创建一个类(除非你有你想要访问的特定变量。
    只需在此处执行您正在执行的操作,但在 View Controller 中,这将是 self. :)

    您可能想看看:How to load a UIView using a nib file created with Interface Builder

    编辑 2

    好的,我想我明白了:
  • 删除 Storyboard 中的 MyCustomView。
  • 创建一个 MyView 类或附加到 Storyboard 中名为“View”的 View 的任何内容。
  • 在你的类的 init 方法中,你实例化你的 MyCustomView Nib
  • 像你做的那样将生成的 UIView 添加到 View 堆栈中。

  • self 将是 MyView(出现在 Storyboard 中),MyCustomView 不会出现在 Storyboard 中,而是在 MyView.h 的 init 方法中以编程方式创建

    您必须以编程方式添加约束。这是一个有用的帖子:Adding View Programatically With Auto Layout Gives 'NSGenericException', reason: 'Unable to install constraint on view

    关于ios - 使用带有 Storyboard 的自定义 View 而不添加两次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21069837/

    相关文章:

    ios - 模态呈现的 UISplitViewController 永远不会被释放

    iphone - iOS - UIImageView 动画内存泄漏?

    iphone - 如何在循环内动态命名 UIButtons 以及如何制作动画

    javascript - 让 NSXMLParser 跳过一个元素

    iOS 7 兼容应用程序在启动时崩溃。为什么?

    ios - 将 UIDocumentIntractionController 推送到 UINavigationController

    ios - 为什么登录时未调用 "ASAuthorizationControllerDelegate"?

    ios - 在 Swift 中获取联系人姓名和电话号码

    ios - View Controller 之间的扩展圆圈动画过渡

    iphone - UITableViewHeaderFooterView : Unable to change background color