在使用程序化故事板打开的视图之间传递变量

时间:2014-09-24 20:52:53

标签: ios objective-c variables global-variables

我目前正在使用以下代码打开我的新视图:

NSString * storyboardName = @"Main";
UIStoryboard *storyboard = [UIStoryboard storyboardWithName:storyboardName bundle: nil];
UIViewController * vc = [storyboard instantiateViewControllerWithIdentifier:@"secondViewController"];
[self presentViewController:vc animated:YES completion:nil];  

我希望能够使用类似于下面发布的代码将变量的值传递给SecondViewController:

ViewControllerB *viewControllerB = [[ViewControllerB alloc] initWithNib:@"ViewControllerB" bundle:nil];
viewControllerB.isSomethingEnabled = YES;
[self pushViewController:viewControllerB animated:YES]; 

但我是Objective-C& S的新手。 iOS编码,不知道怎么做。那么如何使用我已经拥有的代码(第一个代码块)将SecondViewController中变量的值更改为FirstViewController中变量的值。所有帮助表示赞赏。

1 个答案:

答案 0 :(得分:0)

假设您的第二个视图控制器属于MyCustomViewController类型,请更改

UIViewController * vc = [storyboard instantiateViewControllerWithIdentifier:@"secondViewController"];

MyCustomViewController * vc = [storyboard instantiateViewControllerWithIdentifier:@"secondViewController"];

无关的说明,我会改变

MyCustomViewController * vc = [storyboard instantiateViewControllerWithIdentifier:@"secondViewController"];

MyCustomViewController * vc = [storyboard instantiateViewControllerWithIdentifier:NSStringFromClass([MyCustomViewController class])];

您需要更改故事板中的标识符才能匹配。如果你这样做,你将保留一些类型信息,而不是使用脆弱的硬编码字符串。 (仅供参考,这些代码都没有经过测试,只是在这里写出来。)