描述:
具体功能是: 我有一个按钮,点击会出现一个弹窗,弹窗上也有按钮,如果我点击了按钮弹出弹窗然后就不做任何操作,弹窗会在2秒后自动消失,如果在2秒内点了弹窗上的按钮,那么会重新计时2秒,如果没操作就消失。
用Android的话可以同过handler延时发送消息实现。 就是点一下按钮,执行一次下面操作
handler.removeMessages(1);
handler.sendEmptyMessageDelayed(1, 2000);
发送一个2秒延时的消息,如果2秒内有操作,就移除这个消息,重新发一个2秒延时的消息,就能实现上面的功能。
不知道IOS如何实现。请大牛解答下0.0
解决方案1:
#import "ViewController.h"
@interface ViewController ()
@property (nonatomic, strong) NSTimer *timer;
@property (weak, nonatomic) IBOutlet UILabel *timerLabel;
@property (nonatomic, assign) int count;
@end
@implementation ViewController
- (IBAction)startBtnClick:(id)sender {
if (self.timer) {
[self.timer invalidate];
self.timer = nil;
}
self.count = 0;
self.timer = [NSTimer scheduledTimerWithTimeInterval:1.0f target:self selector:@selector(repeatShowTime:) userInfo:@"admin" repeats:YES];
}
- (IBAction)stopBtnClick:(id)sender {
if (self.timer) {
[self.timer invalidate];
self.timer = nil;
}
self.count = 0;
self.timerLabel.text = @"00:00";
}
- (IBAction)pauseBtnClick:(id)sender {
[self.timer setFireDate:[NSDate distantFuture]];
}
- (IBAction)continueClick:(id)sender {
[self.timer setFireDate:[NSDate date]];
}
- (void)viewDidLoad {
[super viewDidLoad];
}
- (void)repeatShowTime:(NSTimer *)tempTimer {
self.count++;
self.timerLabel.text = [NSString stringWithFormat:@"%02d:%02d",self.count/60,self.count%60];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
}
- (void)dealloc {
if (self.timer) {
[self.timer invalidate];
self.timer = nil;
}
}
这是控制器代码,一个简单定时器的实现,storyboard上面的空间你根据代码添加就行了,你看下你需要的功能这些代码能不能用
可以的,你在方法里写就好了。当事件触发的时候,计时器停止或移除或重新开始,你可以找一下类似于ios计时器之类的demo看下,我觉得计时器的功能和你需要的功能挺像的。
解决方案3:开个线程就可以实现了
解决方案4: NSTimer
+ (NSTimer *)scheduledTimerWithTimeInterval:(NSTimeInterval)ti target:(id)aTarget selector:(SEL)aSelector userInfo:(nullable id)userInfo repeats:(BOOL)yesOrNo;