Objective-C,显示由UIButton激活的NSTimer

时间:2014-05-06 09:23:00

标签: objective-c xcode uibutton nstimer countdowntimer

我正在为学校开展一个项目,其中包括一组创建用作倒数计时器的NStimers的按钮。理想情况下,时间将显示为启动计时器的UIButton的标题。

到目前为止,我只能在设置显示时间时才能完成这项工作,而是指向UIButton的特定实例,而不是以某种方式传递UIButton参数。 我还声明了“time”NSString,它保存了NSTimer计算出的当前显示值。这不是最终实现的方式,我只是将它设置为这样只是让它部分工作。

其中一个按钮的代码:

b1 = [[UIButton alloc]
             initWithFrame:CGRectMake(neutral.frame.size.width * 0.56, neutral.frame.size.height * 0.18, neutral.frame.size.height * 0.64, neutral.frame.size.height * 0.64)];
    [b1.titleLabel setFont:[UIFont fontWithName:@"Helvetica-Bold" size:35.0]];
    [b1 setBackgroundImage: forState:UIControlStateNormal];

按钮按下操作调用的方法:

-(void)buttonClicked:(id)sender
{ 
    //do stuff


timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(timerFired) userInfo:[NSNumber numberWithInt:t] repeats:YES];  }

NSTimer计时器触发方法:

-(void)timerFired
{    
if((curMin>0 || curSec>=0) && curMin>=0)
{
    if(curSec==0)
    {
        curMin-=1;
        curSec=59;
    }
    else if(curSec>0)
    {
        curSec-=1;
    }
    if(curMin>-1)
    {
    time = [NSString stringWithFormat: @"%d%@%02d",curMin,@":",curSec];
    [b1 setTitle:time forState:UIControlStateNormal];
    }

}
else
{

    [b1 setTitle: nil forState:UIControlStateNormal];

    [timer invalidate];

   }
}

我希望对于我想要完成的事情已经足够清楚了。我有点惊讶,因为我找不到任何东西可以帮我解决这个问题。我可以灵活地改变它的工作原理。真正重要的是每个按钮都可以启动一个独特的倒数计时器。

我确信这段代码很草率,但Objective C对我来说相对较新,所以任何帮助都会受到赞赏。

1 个答案:

答案 0 :(得分:1)

不要将时间存储为分钟/秒,只需使用秒,因为所有大于60 逻辑真的很乏味不是。

我已经选择调用实例变量_secondsLeft,所以当我在6个月内查看代码时,我会知道这意味着什么:

-(void)timerFired
{    
    NSString *formatted = @"";
    if (secondsLeft > 0)
    {
        secondsLeft--;
        formatted = [NSString stringWithFormat:@"%d:%02d", (secondsLeft / 60), (secondsLeft % 60)];
    } else {
        [timer invalidate];
    }
    [b1 setTitle:formatted forState:UIControlStateNormal];
}