【发布时间】:2015-05-27 04:08:16
【问题描述】:
我是 iOS 开发的新手,我正在编写一个带有倒数计时器的应用程序。我希望用户能够点击时间来设置它,所以我使用了UIButton,因为这似乎是最简单的事情。我在这个网站上看到了有关使用“UILabel”作为计时器并使用轻击手势来检测用户触摸“UILabel”的问题,但似乎大多数人建议使用UIButton。
我遇到的问题是我将UIButton 文本初始化为 00:00,然后在用户选择时间时更改它。计时器设置为每 0.25 秒(重复)关闭一次,并且处理程序每次检测到时间已更改至少 1 秒时都会更新按钮中的文本。
我遇到的问题是在更新 UIButton 文本之间,UIButton 文本恢复到 00:00。例如,如果计时器设置为 10 分钟 (10:00),则 UIButton 文本执行以下操作:
10:00(开始)
00:00(大约 0.5 秒)
09:59(1 秒后)
00:00(大约 1.5 秒后)
等
如果我使用UILabel,则不会发生这种情况。以这种方式使用UIButton 是否存在固有问题?我应该只使用UILabel 并弄清楚如何做一个轻击手势吗?任何帮助将不胜感激!
这是我更新 UIButton 文本的代码(我正在使用通知事件):
- (void)timerChangedNotification:(NSNotification *)notification
{
Timer *timer = (Timer *) notification.object;
if ([[notification name] isEqualToString:@kGameClockTimer]) {
NSInteger timeInMinutes = (timer.currentTimeInSeconds / 60) % 60;
NSInteger timeInSeconds = timer.currentTimeInSeconds % 60;
if ((self.lastTimeInMinutes != timeInMinutes) || (self.lastTimeInSeconds != timeInSeconds)) {
self.lastTimeInMinutes = timeInMinutes;
self.lastTimeInSeconds = timeInSeconds;
// this label is to see if the same behavior happens using a label
self.timerLabel.text = [NSString stringWithFormat:@"%02ld:%02ld",
(long)timeInMinutes, timeInSeconds];
self.timerButton.titleLabel.text = [NSString stringWithFormat:@"%02ld:%02ld",
(long)timeInMinutes, timeInSeconds];
}
}
}
编辑: 根据下面的一些 cmets,我在将“UIButton”设置为这样时更改了代码:
[self.timerButton setTitle:[NSString stringWithFormat:@"%02ld:%02ld", (long) timeInMinutes, (long) timeInSeconds] forState:UIControlStateNormal];
这确实让我更接近了,因为我在更新之间没有得到 00:00,但文本仍然在更新之间“闪烁”。我怀疑这与 forState 有关。我还需要为其他州设置标题吗?
编辑:
好的,我找到了解决“闪烁”按钮问题的方法。我不得不补充:
[UIView setAnimationsEnabled:NO]; 在我的代码中。
感谢大家的帮助!
【问题讨论】:
-
你能贴一些代码吗?
-
对不起,我应该这样做的,但是已经很晚了,我很累。我更新了我的帖子。
标签: ios objective-c timer uibutton uilabel