Passing variables between view controllers

混江龙づ霸主 提交于 2019-12-17 10:59:32

问题


I am using this function to switch between views in Xcode 4.3.

[self performSegueWithIdentifier:@"NextView" sender:self];

I would like to pass some parameters between pages. How can I do that?


回答1:


After performSegueWithIdentifier:sender: your view controler will call

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

assuming your new view controller has some propertys to set:

if ([[segue identifier] isEqualToString:@"NextView"]) {
    MyViewController *myVC = [segue destinationViewController];
    myVC.propertyToSet = // set your properties here
}



回答2:


This question has a very nice and correct explanation of passing data between view controllers:

Passing Data between View Controllers




回答3:


Here is the answer from Pfitz, but I made it a little easier to understand for folks who are new to Objective-C using an example:

  1. In your destinationViewController.h file add property setting for variable to 'receive' value from your source controller.m file

    @property (nonatomic) int billIdReceivingVote;
    
  2. Import your destinationViewController.h to your sourceViewController.m file:

    // VOLViewController.m
    #import "VOLVoteViewController.h
    
  3. Add prepareForSegue method to your sourceViewController.m file and pass the variables

    - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
    {
        VOLVoteViewController *myDestinationViewController = [segue destinationViewController];
    
        // myDestinationViewController.variable = sourceViewController variabe
        myDestinationViewController.billIdReceivingVote = [self.idOfBillSelected intValue];
    }
    


来源:https://stackoverflow.com/questions/11577484/passing-variables-between-view-controllers

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!