如何解决iOS中的UI元素如何从没有线程的循环中更新?
| 我想从循环中更新标签,例如:- (void)viewDidLoad {
[super viewDidLoad];
int i=0;
while (1) {
i++;
[NSThread sleepForTimeInterval:0.05]; // do some computation,[myLabel setText:[NSString stringWithFormat:@\"%d\",i]]; // show the result!
[self.view setNeedsDisplay];
}
}
假设完成了大量的计算而不是睡眠。
我不想在后台进行计算的开销。
Windows处理该问题的等效项是.DoEvents,如以下示例所示:
http://www.tek-tips.com/viewthread.cfm?qid=1305106&page=1
iOS中是否有类似的解决方案?
[self.view setNeedsDisplay]根本不起作用!
必须有某种方法可以在主线程中按受控的时间表处理来自iOS的应用程序事件...就像Windows中的.DoEvents一样,尽管它的所有缺点对于某些简单的应用程序也非常有用。
我想这就像一个游戏循环,但带有UI组件。
解决方法
您将执行以下操作:
-(void) incrementCounter:(NSNumber *)i {
[myLabel setText:[NSString stringWithFormat:@\"%d\",[i intValue]]]; // show the result!
[self performSelector:@selector(incrementCounter:) withObject:[NSNumber numberWithInt:i.intValue+1] afterDelay:0.05];
}
- (void)viewDidLoad {
[super viewDidLoad];
// start the loop
[self incrementCounter:[NSNumber numberWithInt:0]];
}
这里的基本思想是在稍有延迟0.05后增加计数器,以使主UI线程有机会刷新所有UI事件,这弥补了Windows世界中显式调用.DoEvents的不足。
, 我假设您想使用标签实现计数器?例如,您可以使用NSTimer调用一种方法,该方法每隔X毫秒更新一次计数器。
, 如果要更新UI组件,请在iOS
中使用NSTimer
。
NSTimer* myTimer = [NSTimer scheduledTimerWithTimeInterval: 60.0 target: self
selector: @selector(callAfterSomeSecond:) userInfo: nil repeats: YES];
实现callAfterSomeSecond:如下所示:
-(void) callAfterSomeSecond:(NSTimer*) timer
{
static int counter = 0;
if(counter == 100)
{
[timer invalidate];
}
[myLabel setText:[NSString stringWithFormat:@\"%d\",counter ]];
[self.view layoutSubviews];
counter++;
}
, 在您的代码中,while循环在Main线程中运行,并且UI更新也应该在Main线程中完成,因此,在循环运行时,Main线程有点\'blocked \'(忙),因此UI更新无法执行。
我想我想说的不是你想要的。要解决该问题,您必须将繁重的计算工作放在另一个线程中,例如使用NSOperation或GCD。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。