简体   繁体   中英

Passing data between view controllers in storyboards using segue

I'm new at iOS development and after reading many tutorials about passing variables and i still need your help.

This function in my PP.m file:

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


if ([segue.identifier isEqualToString:@"Btn1Transport"])
{
   [segue.destinationViewController setMyData:(50)];
    NSLog(@"Transporter1");
}

if ([segue.identifier isEqualToString:@"Btn2Transport"])
{
   [segue.destinationViewController setMyData:(100)];
    NSLog(@"Transporter2");
}

}

This is in my Category.m file:

- (void)viewDidLoad{

[super viewDidLoad];

recipeLabel.text = @"Hello"; //for test, is working

}

-(void)setMyData:(int)myData
{

    NSLog(@"Happines %d",myData);
    NSString* result = [NSString stringWithFormat:@"%d", myData];
    recipeLabel.text = result; //not working
}

The problem is at the line NSLog(@"Happines %d",myData); my data prints just fine, but not gets set to recipeLabel. So for testing if it works i made recipeLabel.text = @"Hello"; and the label is just fine. What am I doing wrong? And sorry for the beginner question.

No, you can't write to the TextLabel directly from the prepareForSegue event, the value will be overwritten when the destination view controller will load ...

You have to set a variable in the destination view controller and then you have to set the value of your label equal to the value of the variable in the viewDidLoad event of the destination view controller to make it works ...

//The variable myIntVar is a private variable that should be declared in the header file as private 
- (void)viewDidLoad{

[super viewDidLoad];

recipeLabel.text = myIntVar; //set the value equal to the variable defined in the prepareForSeque
}

-(void)setMyData:(int)myData
{

    NSLog(@"Happines %d",myData);
    NSString* result = [NSString stringWithFormat:@"%d", myData];
    myIntVar = result; 
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM