load view from a nib

╄→尐↘猪︶ㄣ 提交于 2019-12-11 10:14:46

问题


I've been struggling with this for a while and I think the solution is really simple, but I just can't get it right. I have a UIViewController, which has its view and now I would like to add a subview to it. Subview should be loaded from a nib. I've followed the steps described here, ie.:
1. Create MyView class which is a subclass of UIView
2. Declare IBOutlet properties in MyView
3. Make .xib file, where File Owner is set to UIViewController and View class set to MyView
4. Connect outlets
5. In MyViewController, viewDidLoad method :

NSArray *nibViews = [[NSBundle mainBundle] loadNibNamed:@"MyView" owner:self options:nil];
MyView *mView;
for (id view in nibViews) {
   if ([view isKindOfClass:[MyView class]]) {
      mView = (MyView*) view;   
    }
}
[self.view addSubview:mView];

mView is loaded successfully, but when I try to add it as a subview I get EXC_BAD_ACCESS. I've even added: mView = [(MyView*) view retain]; but that doesn't help.

What am I doing wrong?


回答1:


i'm not sure of your point 3:

Make .xib file, where File Owner is set to UIViewController and View class set to MyView

the file owner shouldn't be the uiviewcontroller, but the MyView class




回答2:


Don't worry...

You don't need to take separate nib file and referencing to the myView class again. Simply you can drag UIView from library into your current viewController's xib, and then u can simply connect the view from current view to the xib.

See below images:




回答3:


In my case, I didn't want my view controller to have any knowledge of the IBOutlets from my view's .xib. I wanted my view subclass to own the IBOutlets. Unfortunately UIView doesn't have an initWithNibName: method, so I just created my own category.

Here's what I did:

  • In IB, click on your main UIView, and in the Identity Inspector, set the class to your subclass
  • In IB, click on File's Owner, and in the Identity Inspector, set the class to your subclass
  • Use your new category method initWithNibName: to instantiate your view.

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.



来源:https://stackoverflow.com/questions/9545962/load-view-from-a-nib

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