【问题标题】:How to update UILabel如何更新 UILabel
【发布时间】:2012-05-13 04:04:41
【问题描述】:

我有一个要更新的 UILabel。它已通过 ctrl-cicking 并通过 XIB 文件添加到类中。我在等待短暂的延迟后尝试更新标签文本。到目前为止,除了下面的代码之外,没有其他任何事情发生。但是,当我运行它时,模拟器会暂时空白并直接将我带到最后更新的文本。它没有向我显示 100 只是 200

如何让标签按我想要的方式更新。最终我试图在标签内设置一个递减计时器。

从 XIB 链接到头文件的标签:

@property (strong, nonatomic) IBOutlet UILabel *timeRemainingLabel;

在实施中:

- (void)viewDidLoad
{
    [super viewDidLoad];

    self.timeRemainingLabel.text = @"100";
    sleep(1);
    self.timeRemainingLabel.text = @"200";    
}
  • 已合成。

  • XCode 4.3.2、Mac OSX 10.7.3、iOS Simulator 5.1(运行 iPad)、iOS 5

【问题讨论】:

    标签: objective-c ios ios5 uikit


    【解决方案1】:

    您的实现的问题是执行序列在sleep 中没有离开方法。这就是问题所在,因为 UI 子系统在获得将标签设置为 "200" 的命令之前,从来没有机会将标签更新为 "100" 值。

    要正确执行此操作,首先需要在 init 方法中创建一个计时器,如下所示:

    timer = [NSTimer scheduledTimerWithTimeInterval: 1.0 target:self selector:@selector(updateLabel) userInfo:nil repeats: YES];
    

    那么你需要为你的updateLabel方法写代码:

    -(void) updateLabel {
        NSInteger next = [timeRemainingLabel.text integerValue]-1;
        timeRemainingLabel.text = [NSString stringWithFormat:@"%d", next];
    }
    

    【讨论】:

    • 感谢您的回答。这似乎做到了。
    【解决方案2】:

    它永远不会像这样向你显示 100,因为你在这里使用了 sleep,它正在停止你的程序的执行,并且在 sleep 的 1 秒后你正在更新文本。如果你想这样做,那么你可以使用NSTimer

    像这样更改上面的代码:

    - (void)viewDidLoad
    {
        [super viewDidLoad];
    
        self.timeRemainingLabel.text = @"100";
    
        [NSTimer scheduledTimerWithTimeInterval:2.0 target:self selector:@selector(updateLabel) userInfo:nil repeats:NO];
    
    }
    
    - (void) updateLabel
    {
        self.timeRemainingLabel.text = @"200"; 
    }
    

    【讨论】:

    • 感谢您的回答。没想到。
    【解决方案3】:

    在视图尚未加载之前,您的视图不会出现,并且标签 timeRemainingLabel 的文本是 @"200" 时发生这种情况。所以你看不到文本的变化。请改用NSTimer 来执行此操作,并将文本分配给选择器中的标签:

    timer = [NSTimer scheduledTimerWithTimeInterval:timeInSeconds target:self selector:@selector(updateText) userInfo:nil repeats: YES/NO];
    

    并在您的更新方法中,根据您的要求设置最新文本:

    -(void) updateText {
        self.timeRemainingLabel.text = latestTextForLabel;
    }
    

    【讨论】:

    • 感谢您的帮助。我现在明白了:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多