我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; }
我错过了什么?
正如您所知,UIViewController
我们有-initWithNibName:bundle:
一种方法可以将它与xib连接起来.
但是......
当涉及到a时UIView
,你需要使用-loadNibNamed:owner:options:
xib 来加载它.(只是在xib中为视图指定自定义类将不起作用)
创建了一个UIView
名为的子类CustomXIBView
(新文件> Cocoa Touch> Objective-C类 - 子类UIView
)
创建了一个简单的视图用户界面并命名它 CustomXIBView
(新文件>用户界面>查看)
转到CustomXIBView
笔尖
选择View
(左侧工具栏)
选择Show Identity Inspector
(右侧面板中的第3个选项)
指定CustomXIBView
作为自定义类的View
不要做任何CustomXIBView
的File's Owner
在笔尖
拖放对象并将其连接 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];
参考:http://eppz.eu/blog/uiview-from-xib/