我是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”;而且标签很好。我究竟做错了什么?抱歉初学者的问题。
答案 0 :(得分:3)
不,您无法直接从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;
}