[英]How to update UILabel
我有一个要更新的UILabel。 它已通过ctrl删除并通过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
它永远不会向您显示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";
}
实现的问题在于,执行序列在sleep
时不会离开方法。 这是问题所在,因为UI子系统在获得将其设置为"200"
的命令之前从未机会将其标签更新为"100"
"200"
。
要正确执行此操作,首先需要在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];
}
发生这种情况之前,只有在未加载视图并且标签timeRemainingLabel
的文本为@"200"
时,您的视图才会出现。 因此您看不到文本更改。 使用NSTimer
代替,并将文本分配给选择器中的标签:
timer = [NSTimer scheduledTimerWithTimeInterval:timeInSeconds target:self selector:@selector(updateText) userInfo:nil repeats: YES/NO];
然后在更新方法中,根据您的要求设置最新文本:
-(void) updateText {
self.timeRemainingLabel.text = latestTextForLabel;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.