Objective C - loop to change label text

余生长醉 提交于 2019-12-17 07:51:09

问题


i have a loop that looks like this

for(int x=0; x < 10; x++){
    [testLabel setText:[self randomString]];
    sleep(1);
}

The randomString is a method where it returns a random string from an array.

I'm using sleep so it is actually possible to see the label being changed.

The loop works fine but the label only gets updated after the last iteration from the loop.

Does anyone know why this could be? And would there be a way to fix it?


回答1:


Do not call sleep()

Certainly not ever on the main thread and any use of sleep in secondary threads is generally highly questionable.

In this case, just use an NSTimer instance to periodically update the value (as Wilbur said).




回答2:


The UI is only updated at the end of a run loop, of which your loop is running inside of a single iteration of. You should be using an NSTimer instead.




回答3:


To get updated you should run it separately:

for(int x=0; x < 10; x++){
    [self performSelectorOnMainThread:@selector(updateLabel) withObject:nil waitUntilDone:NO];
    sleep(1);
}

- (void) updateLabel {
    [testLabel setText:[self randomString]];
}



回答4:


It's better if you run your string on a background thread

[self performSelectorInBackground:@selector(updateBusyLabel:) withObject:[NSString stringWithFormat:@"Processing ... %i",iteration]];

-(void)updateBusyLabel:(NSString *)busyText {
    [_busyLabel setText:busyText];
}

I wouldn't use sleep(), and the timer is too much work.



来源:https://stackoverflow.com/questions/6325202/objective-c-loop-to-change-label-text

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!