我有两个 View Controller ,MainViewController 和 SecondViewController。
在我的主视图 Controller 中,我将数据传递给第二个 View Controller ,如下所示:
-(IBAction)shareToSocial:(id)sender {
SecondViewController *view2 = (SecondViewsController *)[storyboard instantiateViewControllerWithIdentifier:@"PushToNext"];
view2.secTitle = self.MainTitle;
[self.navigationController setModalPresentationStyle: UIModalPresentationCurrentContext];
[self setModalPresentationStyle:UIModalPresentationCurrentContext];
}
其中 secTitle 和 MainTitle 都是每个 Controller 的 NSString。根据我的阅读,通过将 view2.secTitle 设置为 self.MainTitle,当 SecondViewController 弹出时,我的 view2.secTitle 将具有与 MainTitle 相同的值。因此,如果 MainTitle 是“Hello World”,那么我打开 secondViewController,secTitle 也将是“Hello World”。但是,即使我正在为它设置数据,我也一直在使用 secTitle 为空。
如果我使用 pushViewController 而不是模态,则值可以在两个 Controller 之间正常传递。所以我不确定我在这里做错了什么。
我也尝试过使用 [view2 setSecTitle:MainTitle] 无济于事。
我的 SecondViewController 上没有太多代码,但它看起来是这样的:
-(IBAction)showMessage:id(sender){
NSLog(@"test: %@", self.secTitle);
}
-(IBAction)closeMessage:id(sender){
[self dismissViewControllerAnimated:YES completion:nil];
}
另外,我注意到当我在 SecondViewController 上使用 dismissViewControllerAnimated 关闭它并返回到 MainViewController 时,黑色空白屏幕会显示几秒钟,然后再显示主视图,并且不再检测到 MainViewController 上的触摸事件。
请帮忙。
最佳答案
您可以使用 performSegueWithIdentifier 和 prepareForSegue 吗?如果您在 Storyboard中获得了您的观点并在它们之间设置了一个 segue,给它一个标识符并将样式设置为模态,您应该能够这样做:
-(IBAction)shareToSocial:(id)sender {
[self performSegueWithIdentifier:@"modelToNextSegue" sender:self];
}
然后在 prepareForSegue 方法中传递您的值:
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
SecondViewController *view2 = [segue destinationViewController];
view2.secTitle = self.MainTitle;
}
关于ios - 使用模式时将数据传递给 UIViewController,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19854706/