zoukankan      html  css  js  c++  java
  • iOS中如何使定时器NSTimer不受UIScrollView滑动所影响

    以下是使用 scheduledTimerWithTimeInterval 方法来实现定时器

     

    - (void)addTimer
    {
    NSTimer scheduledTimerWithTimeInterval:2.0 repeats:YES block:^{
    [self nextImage];
    }
    }

     

    该方法会自动为我们实例化的timer添加到当前线程的RunLoop中,并且默认模式是  NSDefaultRunLoopMode 。但当前线程是主线程时, 当scrollView或其子类进行滚动的时候,UIKIT会自动将当前runLoopMode切换为 UITrackingRunLoopMode ,因为runLoop只能在各种Mode之间切换,同一时间只能存在一个Mode,所以你加在 NSDefaultRunLoopMode 中的计时器当然不会走了。
     
    因此,为了设置一个不被UI干扰的Timer,我们需要手动创建一个Timer,再获取到当前线程的Runloop,然后使用RunLoop的 addTimer:forMode: 方法来把Timer按照指定的模式加入到RunLoop中。

     

    - (void)addTimer
    {
    NSTimer *timer = [NSTimer timerWithTimeInterval:2.0 target:self selector:@selector(nextImage) userInfo:nil repeats:YES];
    // 消息循环
    NSRunLoop *runLoop = [NSRunLoop currentRunLoop];
    [runLoop addTimer:timer forMode: NSRunLoopCommonModes];
    }

     

    当加入到commonModes中时,实际上系统是找出commonModes代表的所有Mode,如 NSDefaultRunLoopMode 和 UITrackingRunLoopMode ,让后分别将其加入了这些mode中。
  • 相关阅读:
    dom4j的安装
    OWl本体语言学习笔记
    java学习笔记之链表(约瑟夫问题)
    C#打开指定文件夹及下载文件代码示例
    如何把phpStorm打造成自己的专属IDE
    SQL和TSQL之间的区别
    整数的划分(分治递归)
    整数的划分(变形)(分治递归)
    子序列 (Data_Structure)
    找球号(Hash)
  • 原文地址:https://www.cnblogs.com/bigant9527/p/14025274.html
Copyright © 2011-2022 走看看