我想在我的屏幕上突出按钮,我想更改它们的背景图像,等待几秒钟,恢复背景图像并与下一个按钮相同。
我写了这段代码:
-(void)animateButtons
{
UILabel * lbl = [[UILabel alloc] initWithFrame:CGRectMake(0, scroll.frame.origin.y-20, [UIScreen mainScreen].bounds.size.width, 20)];
[lbl setTextAlignment:NSTextAlignmentCenter];
for(int c=0;c<arr.count&&animationRunning;c++)
{
MenuItem * m = [arr objectAtIndex:c];
[lbl setText:m.name];
MyButton * b = (MyButton*)[self.view viewWithTag:c+1];
NSMutableString * str = [[NSMutableString alloc]initWithString:m.image];
[str appendString:@"_focused.png"];
[b setBackgroundImage:[UIImage imageNamed:str] forState:UIControlStateNormal];
sleep(2.5);
str = [[NSMutableString alloc]initWithString:m.image];
[str appendString:@"_normal.png"];
[b setBackgroundImage:[UIImage imageNamed:str] forState:UIControlStateNormal];
if(c==arr.count-1)
{
animationRunning=false;
}
}
}
以这种方式调用该方法,因此它不会阻塞 UI 线程。
[NSThread detachNewThreadSelector:@selector(animateButtons) toTarget:self withObject:nil];
但它只是改变了第一个按钮的背景,然后什么都没有。
使用 NSLog 我可以看到该方法仍在运行,但按钮没有变化。
我怎样才能做到这一点?
谢谢,抱歉我的英语不好。
最佳答案
您不能从后台线程更改 UI 属性,这会导致各种问题,包括崩溃。为了保留您的原始算法,您可以将 UI 更新分派(dispatch)回主线程。但这不是一个非常有效的线程使用,只需使用一个在主线程上运行的简单 NSTimer 即可。
关于ios - 突出显示屏幕上的按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16855606/