I’m pretty new to iOS, and am attempting to present a view controller from within another view controller as described here:
Stack overflow answer (see third answer)
and also here on Apple’s site
I start with the Hello World Example code. I open up MyViewController.m and modify the updateString() method, adding this code to the end:
{
// Get the application's "window"
UIWindow *window = [UIApplication sharedApplication].keyWindow;
// Get the window's rootViewController (NOTE: Only works on iOS 4.0 or later!)
UIViewController *rootViewController = window.rootViewController;
// Create our new controller
UIViewController *enterNameController = [[UIViewController alloc] initWithNibName:@"HighScore" bundle:[NSBundle mainBundle]];
if (enterNameController != NULL)
{
printf("\nLoaded UIView controller. Installing as actionSheetController...\n\n");
UINavigationController *navigationController = [[UINavigationController alloc]
initWithRootViewController:enterNameController];
// Present out Enter Name for High Score view as a modal view
// [rootViewController presentViewController:navigationController animated:YES]; // iOS 2.0 and newer
[self presentViewController:navigationController animated:YES completion: nil]; // iOS 5.0 and newer
}
}
I have also created a NIB file called “HighScore.xib” that I put with the other NIB files that came with the HelloWorld, and I also added HighScore.xib to the XCode project, and dragged it into the “Copy Bundle Resources” section.
As-is, I get an error when running and entering text into the edit field:
* Terminating app due to uncaught exception ‘NSInternalInconsistencyException’, reason: ‘Could not load NIB in bundle: ‘NSBundle (loaded)’ with name ‘HighScore”
However if I change the final statement to use “rootViewController” instead of “self” then nothing happens. No exception, but no new view is presented either.
Questions:
1) Why won’t my NIB load? I’m obviously doing something wrong here.
2) Why does using “rootViewController” instead of “self” produce different results? Shouldn’t the rootViewController find the same class as “self”?
Note that when using “rootViewController” I get a warning in XCode: “MyViewController’ may not respond to ‘-presentViewController:animated:completion”
I solved this problem by:
a) Using the tutorial here:
http://timneill.net/2010/09/modal-view-controller-example-part-1/
b) Right-clicking and doing “Get Info” on the .xib file in the XCode project, and modifying its Type to be “file.xib” instead of “sourcecode.xib”. Without this second change, it would not load! Bizarre. But this was ultimately the problem!!