如何在UIViewController中添加UINavigationBar?

Con*_*sed 5 iphone exc-bad-access objective-c uinavigationbar uiviewcontroller

我有一个UIViewController班级(说它是XXX).我通过代码以模态方式呈现此视图控制器.

XXX *xxx = [ [XXX alloc] init];
[self presentModalViewController:xxx animated:YES];
[xxx release];
Run Code Online (Sandbox Code Playgroud)

我想在XXX视图的顶部添加导航栏.所以我UINavigationBar在XXX的loadView方法中使用了对象.

UINavigationBar *navBar = [ [UINavigationBar alloc] initWithFrame:CGRectMake(0, 0, 320, 44)];
[self.view addSubview:navBar];
[navBar release];
Run Code Online (Sandbox Code Playgroud)

但是,它会抛出一个错误"EXC_BAD_ACCESS".任何帮助......?

谢谢

Par*_*att 17

选项1:

尝试从名为XXX的viewController的XIB添加导航栏.

选项2:

添加UINavigationController并以模态方式呈现它.

替换你的代码:

XXX *xxx = [[XXX alloc] init];
[self presentModalViewController:xxx animated:YES];
[xxx release];
Run Code Online (Sandbox Code Playgroud)

使用此代码:

XXX *xxx = [[XXX alloc] init];
UINavigationController *navigation = [[UINavigationController alloc] initWithRootViewController:xxx];
[self presentModalViewController:navigation animated:YES];
[navigation release];
Run Code Online (Sandbox Code Playgroud)

希望这对你有所帮助.