【问题标题】:Setting label text in another class在另一个类中设置标签文本
【发布时间】:2012-03-09 01:53:46
【问题描述】:

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

在另一个视图控制器中,我正在创建第一个视图控制器的实例。在这里,我尝试设置标签的文本属性。但它不起作用。我一遍又一遍地检查我的代码,找不到任何丢失的东西。 我尝试以编程方式以及使用界面生成器创建标签。仍然无法设置标签的文本属性。这有什么原因吗?

我在

中创建标签
- (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];

我在这里做错了什么

【问题讨论】:

  • 你如何声明它并从其他类访问它?一点代码永远不会伤害:)

标签: iphone ios uiviewcontroller uilabel


【解决方案1】:

尝试使用中间字符串来执行此操作,如下所示:

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

【讨论】:

  • 编辑:myString.text 到只是 myString
【解决方案2】:

您尝试将字符串分配给 UILabel,您需要将字符串分配给 myLabel.text。此外,您还必须确保 UILabel 是可访问的,因此请确保它是一个属性。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-16
    • 2017-08-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-22
    相关资源
    最近更新 更多