iOS开发中解决UIScrollView滚动时NSTimer失效的问题
来源:互联网 发布:mac安装win10 不断重启 编辑:程序博客网 时间:2024/04/30 07:28
我不知道大家在使用NSTimer的时候有没有发现如果我们滑动ScrollView,NSTimer就会失效。我曾经遇到过这样的问题,但需求是即使滑动scrollView,NSTimer也不能失效,于是就好好地研究了下这个问题。最终发现是NSTimer选择的一个模式的问题。
代码:
[[NSRunLoopcurrentRunLoop]addTimer:self.timerforMode:NSDefaultRunLoopMode];
我们将timer添加到当前的主线程中,并且选择NSDefaultRunLoopMode这个默认的模式。在选择这个默认的模式之后,如果我们不与UI进行交互那么NSTimer是有效的,如果我们与UI进行交互那么主线程runloop就会转到UITrackingRunLoopMode模式下,不能处理定时器,从而定时器失效。让定时器不失效的方式有两种:1.改变runloop的模式(NSRunLoopCommonModes),无论用户是否与UI进行交互主线程的runloop都能处理定时器。2.开启一个新的线程,让定时器在新的线程中进行定义,这时定时器就会被子线程中的runloop处理。
代码:
改变runloop的模式:
self.timer = [NSTimertimerWithTimeInterval:1.0target:selfselector:@selector(updateTimer)userInfo:nilrepeats:YES];
// 添加到运行循环 NSRunLoopCommonModes:占位模式 主线程
[[NSRunLoopcurrentRunLoop]addTimer:self.timerforMode:NSRunLoopCommonModes]; //如果不改变Mode模式在滑动屏幕的时候定时器就不起作用了
在子线程中定义定时器:
[NSThreaddetachNewThreadSelector:@selector(bannerStart)toTarget:selfwithObject:nil];
// 在子线程中定义定时器
- (void)bannerStart{
self.timer = [NSTimerscheduledTimerWithTimeInterval:1target:selfselector:@selector(updateTimer)userInfo:nilrepeats:YES];
[[NSRunLoopcurrentRunLoop]addTimer:self.timerforMode:NSDefaultRunLoopMode];
[[NSRunLoopcurrentRunLoop]run];
}
- (void)updateTimer
{
NSLog(@"当前线程:%@",[NSThreadcurrentThread]);
NSLog(@"启动RunLoop后--%@",[NSRunLoopcurrentRunLoop].currentMode);
NSLog(@"currentRunLoop:%@",[NSRunLoopcurrentRunLoop]);
dispatch_async(dispatch_get_main_queue(), ^{
self.count ++;
NSString *timerText = [NSStringstringWithFormat:@"计时器:%ld",self.count];
self.timerLabel.text = timerText;
});
}
- iOS开发中解决UIScrollView滚动时NSTimer失效的问题
- 解决ios6中UIScrollView不能滚动的问题
- iOS开发学习之NSTimer失效、NSTimer与runloop之间的关系、解密NSTimer
- NSTimer 控制 UIScrollView的定时滚动
- 解决UIScrollView 不能滚动的问题
- iOS中UIScrollView和UIPageControl以及NSTimer的综合使用
- IOS UIScrollView 自动布局的 滚动问题
- IOS开发中NSRunloop跟NSTimer的问题
- IOS开发中NSRunloop跟NSTimer的问题
- IOS开发中NSRunloop跟NSTimer的问题
- iOS开发中NSRunloop跟NSTimer的问题
- IOS开发中NSRunloop跟NSTimer的问题
- iOS开发中 NSRunloop 与NSTimer的问题
- IOS开发中NSRunloop跟NSTimer的问题
- IOS开发中NSRunloop跟NSTimer的问题
- IOS开发中NSRunloop跟NSTimer的问题
- IOS开发中NSRunloop跟NSTimer的问题
- ios scrollView中增加动画效果,自动滚动UIScrollView,利用了NSTimer
- NestedScrollingParent
- javaoop基础知识总结
- 1339
- L1-016. 查验身份证 java
- Java的线程控制方法和线程池
- iOS开发中解决UIScrollView滚动时NSTimer失效的问题
- Spark应用运行流程
- Enable VT-x in your BIOS 怎么解决
- C. Dishonest Sellers
- Ubuntu关于Hadoop2.7.x初步安装时,环境变量的设置
- Android操作数据库的框架-GreenDao基本使用记录
- C++基类派生类
- VS中调用DLL进行测试;vs进行远程调试;python中进行debug调试需要的文件
- WebGis实践(1)