简体   繁体   English

如何将笔尖(.xib)文件与UIView关联?

[英]How do I associate a nib (.xib) file with a UIView?

I have a subclass "s" of UIView. 我有UIView的子类“ s”。 I want to put some buttons and labels on s. 我想在s上放置一些按钮和标签。 How do I associate my UIView subclass with a nib file? 如何将UIView子类与nib文件相关联?

  1. In Interface Builder, create a new xib with the View template. 在Interface Builder中,使用View模板创建一个新的xib。
    • Click on the view in the list of objects in the xib (you should also see "File's Owner and "First Responder"). 单击xib中的对象列表中的视图(您还将看到“文件的所有者和”第一响应者”)。
    • Push Cmd-4 to open the Identity pane of the inspector. 按Cmd-4打开检查器的“身份”窗格。
    • Type your class's name into the "Class Name" field and push return. 在“班级名称”字段中输入班级名称,然后按回车键。

You should be able the drag buttons in. To get at the nib from code, use -[NSBundle loadNibNamed:owner:options:] . 您应该可以使用拖动按钮。要使用代码来实现笔尖,请使用-[NSBundle loadNibNamed:owner:options:] Your view should be the first object in the returned array. 您的视图应该是返回数组中的第一个对象。

In my case, I didn't want my view controller to have any knowledge of the IBOutlets from my view's .xib. 就我而言,我不希望我的视图控制器从我的视图的.xib中了解IBOutlets。 I wanted my view subclass to own the IBOutlets. 我希望我的视图子类拥有IBOutlets。 Unfortunately UIView doesn't have an initWithNibName: method, so I just created my own category. 不幸的是,UIView没有initWithNibName:方法,因此我只是创建了自己的类别。

Here's what I did: 这是我所做的:

  • In IB, click on your main UIView, and in the Identity Inspector, set the class to your subclass 在IB中,单击主UIView,然后在Identity Inspector中,将类设置为子类。
  • In IB, click on File's Owner, and in the Identity Inspector, set the class to your subclass 在IB中,单击“文件的所有者”,然后在“身份检查器”中,将该类设置为您的子类
  • Use your new category method initWithNibName: to instantiate your view. 使用新的类别方法initWithNibName:实例化视图。

And here's the category I created: 这是我创建的类别:

- (instancetype)initWithNibName:(NSString *)nibName
{
    NSArray *arrayOfViews = [[NSBundle mainBundle] loadNibNamed:nibName owner:self options:nil];
    if (arrayOfViews.count < 1) {
        return nil;
    }

    self = arrayOfViews[0];

    return self;
}

Inspired by this post . 受此职位启发。

Note though, that so far the frame will adjust automatically, so unlike the code in the post, I haven't yet had to explicitly set the frame. 但是请注意,到目前为止,框架会自动调整,因此与文章中的代码不同,我还没有明确设置框架。 Also, unlike the post's code, I needed to set owner:self so the IBOutlets would be wired up correctly. 另外,与帖子的代码不同,我需要设置owner:self以便IBOutlets正确连接。

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

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