使用Xib初始化视图 [英] Initialize a view with a xib

查看:112
本文介绍了使用Xib初始化视图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用xib初始化视图.那是一个UIView.所以我有一个xib和一个UIView子类,下面粘贴了初始化代码(initWitFrame nibName).创建视图时,我将xib名称从视图控制器输入到init代码中.

I want to initialize a view with an xib. That is a UIView. So I have a xib and a UIView subclass with the init code pasted below (initWitFrame nibName). I feed the xib name to the init code from a view controller when creating the view.

SubclassUIView *view = [[SubclassUIView alloc]initWithFrame:self.view.bounds nibName:@"xibName"];

我在正确的轨道上吗?到目前为止,XIB的内容尚未随视图一起加载.

Am I on the right track? So far the contents of the xib does not load with the view.

通过将xib中的主视图设置为UIView子类的类类型.

By the way the main view in the xib is set to be the class type of my UIView subclass.

- (id)initWithFrame:(CGRect)frame nibName:(NSString*)nibName
{
    self = [super initWithFrame:frame];
    if (self)
    {
        [[NSBundle mainBundle] loadNibNamed:nibName owner:self options:nil];
        [self addSubview:self.view];
    }
    return self;
}

推荐答案

从NSBundle返回的是一个NSArray(具有可视控件,主要是UIViews).从Appart来看,该代码似乎是正确的.看一个起作用的例子:

What is returned from the NSBundle is an NSArray (of visual controls, mainly UIViews). Appart from that the code seems right. Have a look at a functioning example:

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

        NSArray* nibViews = [[NSBundle mainBundle] loadNibNamed:@"TestView" 
                                                          owner:self 
                                                        options:nil];

        UIView* mainView = (UIView*)[nibViews objectAtIndex:0];

        [self addSubview:mainView];
    }
    return self;
}

这篇关于使用Xib初始化视图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆