UILabel无法更新标签文本

时间:2012-05-10 03:09:48

标签: iphone objective-c ios ios4 ios5

我是ios的新手。我有一个viewController,其中有一个通知观察者。 例如

-(void) myNotificationObFn:(Notification *)noti
{
  /* Here i am trying to change the text of UILabel, which is not working. 
  ie:
    NSString *ns = [NSString stringWithFormat:@"%d", 10];
    mylabel.text = ns;
  */
}

我该如何解决这个问题?

3 个答案:

答案 0 :(得分:3)

-(void) myNotificationObFn:(Notification *)noti
{
    dispatch_sync(dispatch_get_main_queue(), ^{
        NSString *ns = [NSString stringWithFormat:@"%d", 10];
        labelfromtag.text = ns;
        [labelfromtag setNeedDisplay];
   });
}

答案 1 :(得分:1)

如果要更改标签

,请尝试使用标记功能

示例:

如果以编程方式创建标签,请在首次创建标签后设置标签

UILabel *myLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, 100, 50)];
[myLabel setTag:1234];

如果您在XIB或故事板中创建标签,只需更改“标记”字段

即可 这样,你的标签就会得到一个标签“1234”

此后,如果您需要编辑此标签,请在通知方法中输入此代码

UILabel *labelfromtag = (UILabel*)[self.view viewWithTag:1234]; //this code direct label "labelfromtag" to your "myLabel", so your new label here is actually your old label
NSString *ns = [[NSString alloc] initWithFormat:@"%d", 10];

labelfromtag.text = ns;
祝你好运:]

编辑:此外,此通知是否与您的UILabel位于同一个类/控制器中?

答案 2 :(得分:0)

1 - 您的标签是否正确连接到IB?您可以在代码中的其他位置更改文本(例如viewDidLoad)吗?

2 - 您不需要分配字符串,因为您没有将其保留在此方法的范围之外。你可以这样做:

[myLabel setText:[NSString stringWithFormat:@"%d",10]];