如何在以编程方式创建按钮转到下一个视图时在视图中传递数据?

时间:2014-03-02 19:48:08

标签: ios objective-c

我在ViewController中以编程方式创建了一个按钮。当用户点击此按钮时,它将转到名为SecondViewController的新视图控制器。在故事板中使用segue,我知道如何在视图控制器之间传递数据,并且过去已经完成了。

我的问题:如果我没有使用故事板并以编程方式执行此操作,我该怎么做?

SecondViewController有一个名为data的NSString属性。

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.


    UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    [button addTarget:self action:@selector(aMethod:) forControlEvents:UIControlEventTouchDown];
    [button setTitle:@"Show View" forState:UIControlStateNormal];
    button.frame = CGRectMake(80.0, 210.0, 160.0, 40.0);
    [self.view addSubview:button];

}

- (void) prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender{

    //load the street view container
    if ([[segue identifier] isEqualToString:@"firstToSecond"]) {

        //send coordinates to container
        SecondViewController *embed = segue.destinationViewController;
        embed.data = @"test";

    }

}

- (void)aMethod:(UIButton*)button
{
    NSLog(@"Button  clicked.");

    UIViewController *myController = [self.storyboard instantiateViewControllerWithIdentifier:@"SecondViewController"];
    [self.navigationController pushViewController: myController animated:YES];

    //I get an error on these 2 lines of code within Xcode.
    MyCustomSegue *segue = [[MyCustomSegue alloc] initWithIdentifier:@"firstToSecond" source:self destination:SecondViewController];
    [self prepareForSegue:segue sender:sender];
    [segue perform];

}

在xcode中,我在这两行上出错:

    MyCustomSegue *segue = [[MyCustomSegue alloc] initWithIdentifier:@"firstToSecond" source:self destination:SecondViewController];
    [self prepareForSegue:segue sender:sender];

有什么建议吗?

2 个答案:

答案 0 :(得分:3)

如果要使用[self.navigationController pushViewController:myController animated:YES]将viewController添加到hierarchie,则无需以编程方式创建segue。

在推送destinationViewController之前调用

prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender,使您有机会在屏幕上显示之前修改或传递数据。所以不要手动调用此功能。您需要做的就是将代码从那里移到

之间
UIViewController *myController = [self.storyboard instantiateViewControllerWithIdentifier:@"SecondViewController"];
myController.data = @"test";
[self.navigationController pushViewController: myController animated:YES];

答案 1 :(得分:2)

为什么不在StoryBoard中创建你的segue?只需从源VC的viewController图标(viewController底部的黄色图标)按住Ctrl键拖动到目标viewController中的某个位置。给这个segue一个标识符(即segueToVC2)

现在以编程方式在您的aMethod中调用此segue:

- (void)aMethod:(UIButton*)button
{
  [self performSegueWithIdentifier:@"segueToVC2" sender:button];
}
  

当我们将segue id定义为segueToVC2时,我们也需要在prepareForSegue中使用它

- (void) prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender{
    //load the street view container
    if ([[segue identifier] isEqualToString:@"segueToVC2"]) {
        //send coordinates to container
        SecondViewController *embed = segue.destinationViewController;
        embed.data = @"test";
    }
}