NSTimer 遇上scrollview

来源:互联网 发布:财经论坛 知乎 编辑:程序博客网 时间:2024/06/04 19:10


不知道大家使用NSTimer的时候,是怎样初始化的,一般来说有以下两种方法:

1:scheduledTimer方法

 NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:1.0f repeats:YES block:^(NSTimer * _Nonnull timer) {    }];

这种方法创建的timer会自动添加到当前的runloop里面去,而且runloop的运行模式kCFRunLoopDefaultMode。这样的timer当遇上scrollView并拖拽时,RunLoop就切换到UITrackingRunLoopMode模式,而在每次调用 RunLoop 的主函数时,只能指定其中一个 Mode,这个Mode被称作 CurrentMode。 所以定时器就不起作用了,也就卡主不动,等停止scrollview的滑动,才会继续计时。那如果要在操作scrollview时不影响timer的计时,就可以用上第二种初始化方法了。

2:timerWithTime方法

NSTimer *timer1 = [NSTimer timerWithTimeInterval:1.0f repeats:YES block:^(NSTimer * _Nonnull timer) {    }];    [[NSRunLoop currentRunLoop] addTimer:timer1 forMode:NSRunLoopCommonModes];

使用这种发放时要注意记得把timer添加到RunLoop中去,并且对于RunLoop的mode也要做相应的设置。

如果对RunLoop没什么概念,只闻其名不见其形的,建议好好看一下RunLoop。

原创粉丝点击