Load NIB from variable

こ雲淡風輕ζ 提交于 2019-12-11 23:48:44

问题


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


回答1:


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];



回答2:


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



来源:https://stackoverflow.com/questions/5417889/load-nib-from-variable

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