IOS怎么样实现Android handler功能

iOS 码拜 8年前 (2016-06-05) 1553次浏览
具体功能是: 本人有一个按钮,点击会出现一个弹窗,弹窗上也有按钮,假如本人点击了按钮弹出弹窗然后就不做任何操作,弹窗会在2秒后自动消失,假如在2秒内点了弹窗上的按钮,那么会重新计时2秒,假如没操作就消失。
用Android的话可以同过handler延时发送消息实现。  就是点一下按钮,执行一次下面操作
handler.removeMessages(1);
handler.sendEmptyMessageDelayed(1, 2000);
发送一个2秒延时的消息,假如2秒内有操作,就移除这个消息,重新发一个2秒延时的消息,就能实现上面的功能。
不知道IOS怎么样实现。请大神解答下0.0IOS怎么样实现Android handler功能
解决方案

5

NSTimer
+ (NSTimer *)scheduledTimerWithTimeInterval:(NSTimeInterval)ti target:(id)aTarget selector:(SEL)aSelector userInfo:(nullable id)userInfo repeats:(BOOL)yesOrNo;

5

开个线程就可以实现了

10

可以的,你在方法里写就好了。当事件触发的时候,计时器停止或移除或重新开始,你可以找一下相似于ios计时器之类的demo看下,本人觉得计时器的功能和你需要的功能挺像的。

20

#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上面的空间你根据代码添加就行了,你看下你需要的功能这些代码能不能用


CodeBye 版权所有丨如未注明 , 均为原创丨本网站采用BY-NC-SA协议进行授权 , 转载请注明IOS怎么样实现Android handler功能
喜欢 (0)
[1034331897@qq.com]
分享 (0)