美文网首页
Swift中Timer

Swift中Timer

作者: 向日葵的夏天_summer | 来源:发表于2018-11-21 14:13 被阅读0次

1.初始化定时器

timer = Timer.scheduledTimer(timeInterval: 3.0, target: self, selector: #selector(timerAction), userInfo: nil, repeats: true)

2.暂停,开启定时器

timer?.fireDate = Date.distantFuture    // 暂停
timer?.fireDate = Date.init(timeIntervalSinceNow: 3.0) //3秒后开启

3.停止定时器

timer?.invalidate()

4.在滑动页面上的列表时,timer会暂停的原因,以及解决办法

  • 原因

在滑动时 当前线程的runloop切换了mode用于列表滑动,导致timer暂停;runloop中的mode主要用来指定事件在runloop中的优先级,默认是default;

  • 解决
    • 方法一:

      将timer加入到runloop的commonModes中,

        RunLoop.current.add(timer!, forMode: .commonModes)
      
    • 方法二:

      将timer放在另外一个线程中,然后开启另外一个线程的runloop,这样可以保证与主线程互不干扰,

        DispatchQueue.global().async {
            self.timer = Timer.scheduledTimer(timeInterval: 3.0, target: self, selector: #selector(self.timerAction), userInfo: nil, repeats: true)
            RunLoop.current.run()
        }
      

相关文章

  • Swift中Timer

    1.初始化定时器 2.暂停,开启定时器 3.停止定时器 4.在滑动页面上的列表时,timer会暂停的原因,以及解决...

  • RxSwift之Timer

    首先,我们先来看看Swift中创建Timer的几种方式 1.Timer的方式 target action 这种方式...

  • swift 视频录制时间 Timer (时间器)

    swift (时间器) Timer 的详细使用 // 开启计时器 var timer: Timer? 使用: t...

  • Timer in swift

    Timer() 若要用controller生命周期控制定时器的开始结束,停止函数必须在控制器类中的直接控制,不能在...

  • RxSwift中的Timer

    RxSwift中的Timer 我们在项目中经常会用到定时器,先来看下swift中使用定时器的几种方式: Timer...

  • IOS&swift中#selector的怪异语法

    #selector()里面的参数是需要调用的方法名。 在Swift中,#selector常用于Timer和UIBa...

  • 解决Timer或者CADisplayLink的释放问题

    转载自:饼哥IT 在swift中,如果使用了Timer或者CADisplayLink,每次在deinit方法里面去...

  • Swift 5.x DispatchSourceTimer

    swift下使用timer防止crash 定义: 开始、暂停和销毁

  • Swift_Timer

    定时器的简单使用 注意:Timer 的Action 的方法是objc方法,否则不调用。

  • Swift GCD Timer

    众所周知,NSTimer 因为依赖于RunLoop去执行,而RunLoop本身工作很繁重,不能确保Timer及时执...

网友评论

      本文标题:Swift中Timer

      本文链接:https://www.haomeiwen.com/subject/oiqcqqtx.html