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中。
  • 相关阅读:
    如何去重一个Oracle表
    配置Eclipse来开发Java 程序
    在windows上使用opera mini
    Oracle OLAP 介绍
    一个Batch作业调度系统构思
    how to Use Subversion with TortoiseSVN
    java official Design Pattern
    how to install ubuntu OS combined with Windows
    确保DWBI项目成功的几个关键点
    spinner 读取sqlite
  • 原文地址:https://www.cnblogs.com/bigant9527/p/14025274.html
Copyright © 2011-2022 走看看