简体   繁体   中英

Programmatically created UIViewController loading an Interface builder view.xib file

How to load an interface builder created view from a programmatically created UIViewController? I'm using Objective-C.

I was able to start with a reference project that did not use the interface builder, so I have no storyboard. I have successfully loaded views programmatically, but would like to be able to load some that were interface builder created.

More detail: I have 2 view controllers A and B. I'm currently in A. I click a button and in that button handler I load Viewcontroller B like this:

self.viewControllerB = [[ViewControllerB alloc] init];
[self.navigationController pushViewController:viewControllerB animated:YES]

I manually created a ViewB with a .m and .h. If I use an initWithFrame wherein i define a bunch of controls and lay them out programmatically, I can successfully call it as described above.

I add a new file to the project, which is a UIView which brings it up in the builder. Drop a TableView onto the view, and now I just want to see this load. I named the xib ViewB.xib, I set the Class to ViewB like the pic below shows (In answer 1)

Whenever you need to load a view from a .xib use this:

First make a nib for the view in interface builder, and be sure to set its custom class to your view's class, see the picture:

在此处输入图片说明

and then load it in your code like this:

MyCustomNibView *myView;
NSArray *topLevelItems = [[NSBundle mainBundle] loadNibNamed:@"MyCustomNibView" owner:nil options:nil];

for (id view in topLevelItems) {
    if ([view isKindOfClass:[MyCustomNibView class]]) {
       myView = (MyCustomNibView *)view;
       break;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM