禁用计时器上的按钮 iOS
Disable a button on a timer iOS
我正在使用 Objective-C 在 XCode 7 上制作一个计时器应用程序,我想在执行以下代码时禁用连接到操作 startCount
的按钮
- (IBAction)startCount:(id)sender {
countInt = 0;
self.Label.text = [NSString stringWithFormat:@"%i", countInt];
timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(countTimer) userInfo:nil repeats:YES];
}
我需要添加哪一行代码来禁用连接到操作 startCount
的按钮?
谢谢
如果我对您的理解是正确的:为了使您的代码更易于理解(并且如果有多个可能 tapped/disabled 的按钮,则避免不愉快的竞争条件),我建议避免使用计时器。相反,考虑 dispatch_after()
这样的:
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 1 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
sender.userInteractionEnabled = false;
});
我们将 sender
传递到方法中,这将是被点击的按钮。 1 * NSEC_PER_SEC
表示 "delay for one second."
您需要通过 enabled
标志 disable
发件人:
((UIButton*)sender).enabled = false;
不要忘记在计时器结束后重新启用按钮。
If the enabled state is NO, the control ignores touch events [...]
替代我在上面的代码中进行的转换:更改您的方法签名以接收 UIButton*
,而不仅仅是一个 id,这样您可以确保转换不会失败。演员表的一个细微变化是改为 UIControl*
。
我正在使用 Objective-C 在 XCode 7 上制作一个计时器应用程序,我想在执行以下代码时禁用连接到操作 startCount
的按钮
- (IBAction)startCount:(id)sender {
countInt = 0;
self.Label.text = [NSString stringWithFormat:@"%i", countInt];
timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(countTimer) userInfo:nil repeats:YES];
}
我需要添加哪一行代码来禁用连接到操作 startCount
的按钮?
谢谢
如果我对您的理解是正确的:为了使您的代码更易于理解(并且如果有多个可能 tapped/disabled 的按钮,则避免不愉快的竞争条件),我建议避免使用计时器。相反,考虑 dispatch_after()
这样的:
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 1 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
sender.userInteractionEnabled = false;
});
我们将 sender
传递到方法中,这将是被点击的按钮。 1 * NSEC_PER_SEC
表示 "delay for one second."
您需要通过 enabled
标志 disable
发件人:
((UIButton*)sender).enabled = false;
不要忘记在计时器结束后重新启用按钮。
If the enabled state is NO, the control ignores touch events [...]
替代我在上面的代码中进行的转换:更改您的方法签名以接收 UIButton*
,而不仅仅是一个 id,这样您可以确保转换不会失败。演员表的一个细微变化是改为 UIControl*
。