如何使用segues在故事板场景之间传递信息?

时间:2013-02-25 13:29:32

标签: ios objective-c ios6

我按照教程创建了2个故事板场景Tutorial,我知道如何使用以下代码将信息从场景1传递到场景2:

-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    Scene2ViewController *destination = 
                  [segue destinationViewController];

    destination.labelText = @"Arrived from Scene 1";
}

但是,我不清楚如何从场景2返回信息(发送布尔值),因为教程正在使用展开来避免创建scene1的新实例,我不能使用下面的scene1上的方法从scene2中分配任何内容:

    -(IBAction)returned:(UIStoryboardSegue *)segue {

Scene2ViewController *destination = 
                      [segue destinationViewController];
        if (destination.thisIsBooleanFromScene2){
       //do something

   }
    } 

1 个答案:

答案 0 :(得分:0)

Scene2ViewController标题中,您可以放置​​当前视图控制器的@property,以便访问其公共变量

所以Scene2ViewController.h

#import "YourPreviousViewController.h"

//add this to your @interface
@property (strong) YourPreviousViewController *parent;

然后在你当前的viewcontroller.m

-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
Scene2ViewController *destination = [segue destinationViewController];
destination.parent = self;
}

然后您可以从returned运行Scene2ViewController方法,或者您可以操纵当前viewcontroller上的公共变量,即parent

编辑:我之前从未见过这样的返回方法,您可以创建一个方法来设置当前视图控制器中所需的变量,然后在Scene2ViewController中实现- (void) viewWillDisappear { }当你按回或转到另一个视图时会运行

//Scene2ViewController.m
- (void) viewWillDisappear {  
[self.parent returnAndSetBool:someBool];

//or if myBoolean in the previous view controller is a public variable you can just go:
//self.parent.myBoolen = someBool;
}

//CurrentViewController.m
- (void) returnAndSetBool: (bool) passbackVariable {
self.myBoolean = passbackVariable;
}