简体   繁体   English

使用segue在情节提要中的视图控制器之间传递数据

[英]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. 我是iOS开发的新手,在阅读了许多有关传递变量的教程之后,我仍然需要您的帮助。

This function in my PP.m file: 我的PP.m文件中的此功能:

- (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: 这是在我的Category.m文件中:

- (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); 问题出在行NSLog(@“ Happines%d”,myData); my data prints just fine, but not gets set to recipeLabel. 我的数据可以正常打印,但没有设置为recipeLabel。 So for testing if it works i made recipeLabel.text = @"Hello"; 因此,为了测试它是否有效,我制作了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 ... 不,您不能直接从prepareForSegue事件写入TextLabel,当目标视图控制器加载时,该值将被覆盖...

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 ... 您必须在目标视图控制器中设置一个变量,然后必须将标签的值设置为等于目标视图控制器的viewDidLoad事件中的变量的值,以使其起作用。

//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; 
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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