如何访问非重复NSTimer的剩余时间

Col*_*tan 5 objective-c uibutton nstimer ios

我正在尝试访问NSTimer X的剩余时间.我想每秒更新一个按钮的标题,以反映剩余时间mm:ss为零.我在这里找不到任何东西.

例如: [btY setTitle:[What to insert here?] forState:UIControlStateSelected];

或者你愿意以不同的方式解决这个问题吗?

Sha*_*mmi 14

你可以使用fireDate

NSTimer *timer = [NSTimer timerWithInterval:1.0 target:self selector:@selector(updateButton) userInfo:nil repeats:YES];


- (void)updateButton:(NSTimer*)timer
{
    float timeRemaining = timer.fireDate.timeIntervalSinceNow;
    // Format timeRemaining into your preferred string form and 
    // update the button text
}
Run Code Online (Sandbox Code Playgroud)


hou*_*oft 2

这通常不是解决问题的方法。

创建一个重复的 NSTimer,设置为您想要更新按钮的分辨率。

例如,如果您希望按钮每秒更改一次直到为零,请创建一个 NSTimer,如下所示:

NSTimer *timer = [NSTimer timerWithInterval:1.0 target:self selector:@selector(updateButton) userInfo:nil repeats:YES];
Run Code Online (Sandbox Code Playgroud)

然后实施updateButton;基本上有一个剩余秒数的计数器,每次updateButton被调用时,计数器减一,并更新按钮的标题。