在buttonClicked方法中,我想将UILabel中的文本颜色设置为黑色,等待三秒钟,然后将颜色设置为绿色。然而,标签永远不会变黑。该方法等待三秒钟,然后 UILabel 文本变为绿色。我认为使用performSelectorOnMainThread可以解决这个问题,但事实并非如此。代码如下。非常感谢,如果我遗漏了一些明显的东西,我深表歉意。
乔恩·R。
-(void) buttonClicked: (id) sender
{
// (UILabel *) letterLabel is instance variable of TestProgramDelegate
[letterlabel performSelectorOnMainThread:@selector(setTextColor:) withObject:[UIColor blackColor] waitUntilDone:YES];
[NSThread sleepForTimeInterval:3];
[letterLabel performSelectorOnMainThread:@selector(setTextColor:) withObject: [UIColor greenColor] waitUntilDone:YES];
}
最佳答案
你的方法是同步改变颜色两次。所有这些代码都在主线程上执行。
// run on main thread
[letterlabel performSelectorOnMainThread:@selector(setTextColor:) withObject:[UIColor blackColor] waitUntilDone:YES];
// buttonClicked: called on mainThread so this is on main thread
[NSThread sleepForTimeInterval:3];
// also on main thread ...
[letterLabel performSelectorOnMainThread:@selector(setTextColor:) withObject: [UIColor greenColor] waitUntilDone:YES];
UI 主线程正在循环并寻找基于按钮单击等事件触发的代码。一旦检测到单击,您的方法就会执行,设置颜色,等待三秒钟,然后在 UI 主循环重绘之前再次设置颜色。由于 UI 不会在中间重绘,因此您永远不会看到第一个。
如果您想这样做,则需要在后台线程上设置颜色,等待三秒钟,然后回调到主线程以更新 UI。
这是相关帖子:
关于IOS 按钮单击并更新 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7883942/