iOS故事板 - 导航控制器不工作

时间:2013-07-29 19:41:26

标签: ios uiviewcontroller uinavigationcontroller storyboard uitableview

我在使用Storyboard的iOS项目中遇到导航控制器问题。

该项目的主要部分是UITabBar。当应用程序第一次加载时,会显示RegisterViewController屏幕:

Register View Controller

当用户点击“注册”按钮时,会发出HTTP POST请求,然后在收到响应(JSON对象)后,屏幕上会显示QuestionnaireViewController:

UIStoryboard *mainStoryboard = [UIStoryboard storyboardWithName:@"MainStoryboard" bundle:nil];

QuestionnaireViewController *questionnaireViewController = [mainStoryboard instantiateViewControllerWithIdentifier:@"QuestionnaireView"];
[questionnaireViewController setModalTransitionStyle:UIModalTransitionStyleCrossDissolve];
[questionnaireViewController setQuestionsAndAnswers:_questionsAndAnswers];

[self presentViewController:questionnaireViewController animated:NO completion:nil];

Questionnaire View Controller

当用户点击QuestionnaireViewController中的单元格时,会向prepareForSegue发送一条消息:sender:

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    UINavigationController *navigationController = segue.destinationViewController;

    AnswersViewController *answersViewController = [[navigationController viewControllers] objectAtIndex:0];

    NSIndexPath *indexPath = [self.tableView indexPathForCell:sender];
    NSArray *answers = [[_questionsAndAnswers objectAtIndex:indexPath.row] objectForKey:@"answers"];

    [answersViewController setAnswers:answers];
}

此时应用程序因以下错误而崩溃: - [AnswersViewController viewControllers]:无法识别的选择器发送到实例。

下面是我的故事板的更全面的概述,这可能有助于理解我出错的地方:

Storyboard

我很难过如何解决这个问题,我希望那里的人能够提供帮助。

谢谢, 尼克

2 个答案:

答案 0 :(得分:9)

首先,您应该呈现导航控制器,而不是其根视图控制器。然后,当您想要使用某些数据填充根视图控制器时,需要将其作为导航控制器的根视图控制器引用:

UINavigationcontroller *questionnaireNavController = [self.storyboard instantiateViewControllerWithIdentifier:@"QuestionnaireNavigationController"];
[questionnaireNavController setModalTransitionStyle:UIModalTransitionStyleCrossDissolve];
QuestionnaireViewController *qvc = (QuestionnaireViewController *)[questionnaireNavController topViewController];
[qvc setQuestionsAndAnswers:_questionsAndAnswers];

[self presentViewController:questionnaireNavController animated:NO completion:nil];

其次,在prepareForSegue:sender:你根本不需要引用导航控制器:

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    AnswersViewController *answersVC = segue.destinationViewController;
    NSIndexPath *indexPath = [self.tableView indexPathForCell:sender];
    NSArray *answers = [[_questionsAndAnswers objectAtIndex:indexPath.row] objectForKey:@"answers"];

    [answersVC setAnswers:answers];
}

答案 1 :(得分:2)

您没有正确获取navigationController。而不是segue.destinationViewControlle r,请使用self.navigationController

通过调用segue.destinationViewController,您将获得一个指向您正在寻找的VC(AnswersViewController)的指针,该指针不理解消息viewControllers,因为它不是UINavigationController。

AnswersViewController也是objectAtIndex:1我相信,请检查一下。