屏幕上的高亮按钮

  • 本文关键字:按钮 高亮 屏幕 ios
  • 更新时间 :
  • 英文 :


我试图在我的屏幕上脱颖而出的按钮,我想改变他们的背景图像,等待几秒钟,恢复背景图像和相同的下一个按钮

我写了下面的代码:

-(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更新分派回主线程。但这并不是一个非常有效的线程使用,只需使用一个运行在主线程上的简单的NSTimer。

如前所述,在主线程上执行所有UI更改。这里有一个选项来完成你想做的事情,不需要NSTimer。

-(void)animateButtons
{
    for (...)
    {
        // set focused state
    }
    [self performSelector:@selector(restoreButtons) withObject:nil afterDelay:2.5];
}
-(void)restoreButtons
{
    for (...)
    {
        // set normal state
    }
}

最新更新