Adding a custom subview (created in a xib) to a view controller's view - What am I doing wrong

﹥>﹥吖頭↗ 提交于 2019-11-29 18:48:22

You need to load it using the -loadNibNamed method. -initWithNibName is only for UIViewControllers.

Add the following code to your MyCustomView init method:

NSArray *subviewArray = [[NSBundle mainBundle] loadNibNamed:@"MyCustomView" owner:self options:nil];
UIView *mainView = [subviewArray objectAtIndex:0];
[self addSubview:mainView];

Remember, if you are initializing an object from a nib, it calls - (id)initWithCoder:(NSCoder *)aDecoder to initialize, so you'll have to override that if you are creating the MyCustomView object within the nib. If you're just doing it with initWithFrame:, then just override that and add the code above. Also, in your nib, make sure you have one top-level UIView, and place all other elements within that (that makes sure that your subviewArray only has one entry).

This will load the views from the nib and add them to the object, and should do the trick.

I think you need to use this method:

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil;

This is because you need to pass it the .xib filename in the "nibNameOrNil".

As hocker said you have to use that method passing in the XIB name (without the extension).

Then you have to control this list:

  • Open the .xib file in IB
  • Click on File Owner and select the correct class (MyCustomView in your case)
  • Hold down control and drag from File Owner to the View (Now the outlet for the view is ok)

Hope it works. Cheers.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!