How do I create UIViewController using Xib-file?

2019-08-05 07:33发布

问题:

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!