How do I create UIViewController using Xib-file?

青春壹個敷衍的年華 提交于 2019-12-11 11:15:41

问题


Sorry if this question has already been answered but I can't find an answer.

I'm creating an app in which I have an UITableViewController and when the accessorybutton in the right side of a cell is selected a new instance of a UIViewController should be created containing the interface found in a .xib-file. The new UIViewController will then be pushed on to the stack and displayed. My question is how do I create the new UIViewController from an existing .xib-file?

This is what I have tried so far: In Xcode: File -> New File -> Cocoa Touch Class -> UIViewController subClass. Checkbox "UITableViewController subclass" unchecked. Checkbox "With XIB for user interface" checked.

This creates a .m, a .h and a .xib file. I created a user interface in the "view" in the .xib-file. Selecting "File's owner" in interface builder shows the newly created UIViewController in "Class Identity".

Some code:

In DetailViewController.m (the new UIViewController):

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
     self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
     return self;
}

In SubViewController.m (the old UITableViewController):

-(void)tableView:(UITableView *)tableView accessoryButtonTappedForRowWithIndexPath:(NSIndexPath *)indexPath{
     DetailViewController *detailViewController = [[DetailViewController alloc] initWithNibName:@"DetailViewController" bundle:nil];
     //Exception thrown at line below
     [self.navigationController pushViewController:detailViewController animated:YES];
     [detailViewController release];
}

Forgot to mention that the .xib-file's name is "DetailViewController.xib".

The code compiles fine but when I run it in the simulator and press an accessorybutton it terminates due to uncaught exception.

What am I missing?

Thanks in advance


回答1:


You shouldn't have to cast this:

DetailViewController
*detailViewController = (DetailViewController*)[[DetailViewController alloc] initWithNibName:@"DetailViewController" bundle:nil];

Are you getting a compiler warning if you don't?




回答2:


The error was in the new view I was trying to display. In the .xib-file I had inserted a MKMapView and when I removed this it all works perfectly.

Thanks again for helping me debug!



来源:https://stackoverflow.com/questions/2072888/how-do-i-create-uiviewcontroller-using-xib-file

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