Load NIB from variable

2019-08-26 20:10发布

I'm trying to load a NIB based on a variable I get from my settings file. This is the code:

//select the right nib name
NSString *nibVar = [nibs objectForKey:@"controller"];

// create the view controller from the selected nib name
UIViewController *aController = [[UIViewController alloc] initWithNibName:nibVar bundle:nil];
aController.modalTransitionStyle = UIModalTransitionStyleFlipHorizontal;
[self presentModalViewController:aController animated:YES];
[aController release];

This unfortunately does not work.

Any ideas here?

Thanks

2条回答
做个烂人
2楼-- · 2019-08-26 20:41

You cannot instantiate "UIViewController" with arbitrary NIBs, you have to instantiate "[whatever your custom view controller class is]" with the NIB for that class.

It's crashing because it's trying to access properties that don't exist in UIViewController.

If you want to do this kind of dynamic view-controller loading, you need to do a bit more work, and use the special Class class method that lets you instantiate an object using a string for the class name, instead of hard-coded.

Sometehing like:

Class viewControllerClass = NSClassFromString( nibVar );
UIViewController* aController = (UIViewController*) [[viewControllerClass alloc] initWithNibName:nibVar bundle:nil];
查看更多
爷、活的狠高调
3楼-- · 2019-08-26 20:44

Make sure the NIB name is correct and does not include the xib extension. It is also case sensitive.

查看更多
登录 后发表回答