在界面构建器中添加的自定义UIView不会加载xib

Lud*_*uda 22 iphone objective-c uiview ios

UIView用xib 创建了自定义.

另外我UIViewController在我的故事板中有一个,我添加了一个UIView并将其类设置为我的自定义UIView.

但是当我运行应用程序时,视图没有其子视图.调试时,所有子视图都为null.

在自定义的.m中UIView,存在以下init方法:

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

    }
    return self;
}

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

    }
    return self;
}
Run Code Online (Sandbox Code Playgroud)

我错过了什么?

sta*_*Man 31

正如您所知,UIViewController我们有-initWithNibName:bundle:一种方法可以将它与xib连接起来.
但是......
当涉及到a时UIView,你需要使用-loadNibNamed:owner:options:xib 来加载它.(只是在xib中为视图指定自定义类将不起作用)


假设:

  1. 创建了一个UIView名为的子类CustomXIBView
    • (新文件> Cocoa Touch> Objective-C类 - 子类UIView)
  2. 创建了一个简单的视图用户界面并命名它 CustomXIBView
    • (新文件>用户界面>查看)

脚步:

  1. 转到CustomXIBView笔尖
  2. 选择View(左侧工具栏)
  3. 选择Show Identity Inspector(右侧面板中的第3个选项)
  4. 指定CustomXIBView作为自定义类View
    • 不要做任何CustomXIBViewFile's Owner在笔尖
  5. 拖放对象并将其连接 CustomXIBView.h

码:

//To load `CustomXIBView` from any `UIViewController` or other class: 
//instead of the following commented code, do the uncommented code
//CustomXIBView *myCustomXIBViewObj = [CustomXIBView alloc] init];
//[myCustomXIBViewObj setFrame:CGRectMake(0,0,320,480)];

//Do this:
CustomXIBView *myCustomXIBViewObj = 
     [[[NSBundle mainBundle] loadNibNamed:@"someView"
                                    owner:self
                                  options:nil]
                            objectAtIndex:0];
[myCustomXIBViewObj setFrame:CGRect(0, 
                                    0, 
                                    myCustomXIBViewObj.frame.size.width, 
                                    myCustomXIBViewObj.frame.size.height)];
[self.view addSubview:myCustomXIBViewObj];
Run Code Online (Sandbox Code Playgroud)

参考:http://eppz.eu/blog/uiview-from-xib/

  • 您好@staticVoidMan,您的建议有效:在IB中设置子视图,然后将loadNibNamed放在uiviewcontroller中.但我正在寻找(也许是错误的,也许这个选项甚至不存在)是创建自定义视图然后在UIViewController的IB中拖动UIView插座,将其类设置为我的自定义UIView而不是写任何码.可能吗? (2认同)