我的ViewController中没有显示UINavigationItem

时间:2013-08-02 15:09:22

标签: ios uinavigationcontroller uinavigationitem ios6.1



我正在使用Xcode在iOS中编写一个简单的应用程序,我正在尝试加载另一个ViewController作为模态。我正在加载模态的原点HomeScreenViewController(继承自UIViewController)源自项目的故事板。
然后,作为对按钮按下事件的响应,我正在加载这个模态:

-(IBAction)onAddButtonPressed:(UIButton *)sender {
    MyAnotherViewController *vc = [[MyAnotherViewController alloc] init];
    [self presentViewController:vc animated:YES completion:nil];
}

MyAnotherViewController未在Storyborad中表示,因为它是一个显示导航栏和文本字段的简单类。代码是(部分代码,其余是Xcode自动生成的方法):

@implementation MyAnotherViewController 

- (void)viewDidLoad {
    [self.navigationItem setTitle:@"Example"];
    [self.view addSubview:[[UITextView alloc]initWithFrame:self.view.bounds]];
}
@end

问题是(也可以在附图中看到)navigationItem由于某种原因未显示。
我还验证了self.navigationItem不是nil而事实并非{{1}}。更进一步,我可以在调试模式下看到标题实际上设置为“示例”。

As can be seen in the screenshot, the UITextView captures the entire screen

非常感谢您的帮助,
干杯...

2 个答案:

答案 0 :(得分:2)

UIViewController的UINavigationItem属性仅在ViewController位于UINavigationController内时使用,因此:

-(IBAction)onAddButtonPressed:(UIButton *)sender {
    MyAnotherViewController *vc = [[MyAnotherViewController alloc] init];
    UINavigationController *navCtl = [[UINavigationController alloc] initWithRootController:vc];
    [self presentViewController:navCtl animated:YES completion:nil];
}

答案 1 :(得分:0)

如果您的MyAnotherViewController不是UINavigationController的子类,或者您尚未手动添加UINavigationItem,则UIViewController无法显示导航项。也许您可以尝试用MyAnotherViewController包裹UINavigationController

// Assume you have adopted ARC
-(IBAction)onAddButtonPressed:(UIButton *)sender {
    MyAnotherViewController *vc = [[MyAnotherViewController alloc] init];
    UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:vc];
    [self presentViewController:nav animated:YES completion:nil];
}

-viewDidLoad的{​​{1}}中,你只需要这样做:

MyAnotherViewController