繁体   English   中英

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

[英]Passing data between view controllers in storyboards using segue

我是iOS开发的新手,在阅读了许多有关传递变量的教程之后,我仍然需要您的帮助。

我的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");
}

}

这是在我的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
}

问题出在行NSLog(@“ Happines%d”,myData); 我的数据可以正常打印,但没有设置为recipeLabel。 因此,为了测试它是否有效,我制作了recipeLabel.text = @“ Hello”; 标签也很好。 我究竟做错了什么? 对于初学者的问题,我们深表歉意。

不,您不能直接从prepareForSegue事件写入TextLabel,当目标视图控制器加载时,该值将被覆盖...

您必须在目标视图控制器中设置一个变量,然后必须将标签的值设置为等于目标视图控制器的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