timer在页面滚动时会造成回调暂停解决方法

2016-12-20  本文已影响698人  没打伞的鱼

使用 +scheduledTimerWithTimeInterval方法生成NStimer会在滚动页面时造成暂停回调.这里讨论一下产生原因和解决方法.

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

使用举例🌰

   //实现定时刷新颜色的功能
 NSTimer * timer = [NSTimer scheduledTimerWithTimeInterval:0.3   
                target:self 
              selector:@selector(setColor)
              userInfo:nil 
                repeats:YES];

产生原因

RunLoop的两种模式

这种NStimer创建方法会默认把NSTimer添加到NSRunLoop上并且设置mode为NSDefaultRunLoopMode.在页面(UIScrollView)滑动的时候,NSRunLoop会自动把Mode切换到 UITrackingRunLoopMode,而NSTimer默认的却是在NSDefaultRunLoopMode上 ,所以这时候的NSTimer是不会执行的。

解决方法

把NSTimer添加到NSRunLoop下的NSRunLoopCommonModes,因为 NSRunLoopCommomModes 模式代表把 timer 加入到所具有"Common"属性标记的模式中. 而 NSDefaultRunLoopMode 和 UITrachingRunLoopMode 这两种模式都具有"Common"属性标记.

//解决方法把NSTimer添加到NSRunLoop下的NSRunLoopCommonModes
[[NSRunLoop currentRunLoop] addTimer:timer forMode:NSRunLoopCommonModes];

参考资料

iOS UITableView 滑动时阻止NSTimer
NStimer

上一篇 下一篇

猜你喜欢

热点阅读