在另一个类中设置标签文本

在我的视图控制器中,我在这里创build一个标签。

在另一个视图控制器中,我创build了第一个视图控制器的一个实例。 在这里,我尝试设置标签的文本属性。 但它不起作用。 我检查了一遍又一遍的代码,找不到任何遗漏。 我尝试以编程方式创build标签以及使用界面生成器。 仍然不能设置标签的文本属性。 有什么理由呢?

我在中创build标签

- (void)viewDidLoad { myLabel = [[UILabel alloc]init]; [myLabel setText:@"Hi"]; [myLabel1 setText:@"Hello"]; [myLabel setFrame:CGRectMake(105, 130, 120, 30)]; [myLabel setBackgroundColor:[UIColor clearColor]]; [myLabel setTextColor:[UIColor whiteColor]]; [myLabel setTextAlignment:UITextAlignmentCenter]; [myLabel setAdjustsFontSizeToFitWidth:YES]; [self.view addSubview:myLabel]; [myLabel release]; } 

在我的第一个视图控制器

 MySecondViewcontroller *showMyViewcontroller = [[ MySecondViewcontroller alloc]initWithNibName:@"MySecondViewcontroller" bundle:nil];; showMyViewcontroller.myLabel = @"I cant set the text"; [self.navigationcontroller pushViewController: showMyViewcontroller animated:YES]; [showMyViewcontroller release]; 

我在这里做错了什么

尝试使用中间string来做到这一点,如下所示:

在FirstViewController中:

 - (void)loadNextView { // load your view SecondViewController *vc = [[SecondViewController alloc] initWithNibName:@"SecondViewController" bundle:nil]; // set a string in your second view (NOT a label) vc.myString = @"Some String"; // push it or whatever [self.navigaitonController pushViewController:vc animated:YES]; [vc release]; } 

在你的SecondViewController.h中

 @interface SecondViewController : UIViewController { UILabel *myLabel; NSString *myString; } @property (nonatomic, retain) UILabel *myLabel; @property (nonatomic, retain) NSString *myString; 

在你的SecondViewController.m中

 - (void)viewDidLoad { // view is now loaded, so we can set the label: myLabel.text = myString; } 

您尝试将一个string分配给一个UILabel,您需要将该string分配给myLabel.text。 你也必须确保UILabel是可访问的,所以确保它是一个属性。