• 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中。
  • 相关阅读:
    路西法效应 和 数学公式输入
    coursera python
    epub java
    How do remove the CD / DVD install as a source for apt-get packages when installing new features?
    vmware player 去除full screen的bar
    Install VMware tools on Ubuntu 20.04 Focal Fossa Linux
    java poi for word
    handwriting ocr
    总结5.22PHP网络与变量
    总结5.12js代表练习题
  • 原文地址:https://www.cnblogs.com/bigant9527/p/14025274.html
Copyright © 2020-2023  润新知