在ViewControllers之间初始化和传递值

时间:2017-02-13 17:43:45

标签: objective-c initialization parameter-passing

我有两个UIViewControllers: TimerViewController EfficiencyViewController (为了简单起见,我们称之为TVC和EVC)

按下按钮时,我试图将某些值(2个NSString对象,1个NSTimeInterval)从TVC传递到EVC。按下按钮后,EVC需要初始化并弹出。 总的来说,我尝试了两种方法。

1。直接传递值(在TVC中)

     UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
EfficiencyViewController *efficiencyViewController = [storyboard instantiateViewControllerWithIdentifier:@"EfficiencyView"];
efficiencyViewController.category = _categoryLabel.text;
efficiencyViewController.desc = _descriptionTextField.text;
efficiencyViewController.duration = [_timer getInterval];
efficiencyViewController.modalTransitionStyle = UIModalTransitionStyleCoverVertical;
[self presentViewController:efficiencyViewController animated:YES completion:NULL];

问题:当我实例化EVC时,我在TVC中保存的值被重置,因此基本上没有数据传递。 (我认为这是因为EVC实际上会弹出屏幕)

2。构建自定义init方法

TVC

EfficiencyViewController *efficiencyViewController = [[EfficiencyViewController alloc] initWithName:_categoryLabel.text desc:_descriptionTextField.text duration:[_timer getInterval]];
[self presentViewController:efficiencyViewController animated:YES completion:NULL];

EVC initWithName方法实现

- (id)initWithName:(NSString *)category desc:(NSString *)theDesc duration:(NSTimeInterval)theDuration {
// self = [super initWithNibName:@"EfficiencyViewController" bundle:nil];
if (self != nil) {
    _category = category;
    _desc = theDesc;
    _duration = theDuration;
}
return self;
}

问题:根本没有传递值。而且通过这种方式,EVC缺少一些主要组件,例如按钮和文本标签。

2 个答案:

答案 0 :(得分:1)

如果你在故事板中有这些,你应该使用故事板segue,并且在TVC的prepareForSegue()中,你从segue对象获得目标视图控制器(即EVC),并且&# 39;设置EVC属性的地方。

答案 1 :(得分:0)

UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Main"
 bundle:nil]; EfficiencyViewController *efficiencyViewController =
 [storyboard
instantiateViewControllerWithIdentifier:@"EfficiencyView"];
efficiencyViewController.category = _categoryLabel.text;
efficiencyViewController.desc = _descriptionTextField.text;
efficiencyViewController.duration = [_timer getInterval];
efficiencyViewController.modalTransitionStyle =
 UIModalTransitionStyleCoverVertical;

使用自我代替 _ ,请参阅此链接https://stackoverflow.com/a/30901681/4912468