📚 开源资源分享——颜佐光的个人书架
✉️ 联系站长
书架 / Mac / swift

Swift定时器的几种实现方式

2021-06-10 11:18 · 约 608 字 · 浏览 2,209 次 · 更新 2021-06-10 11:19swift

Swift定时器的几种实现方式

方式一:

使用performSelector实现

@objc func getCodeAction(sender:UIButton) {
  count = 60
  self.performSelector(inBackground: #selector(timerThread), with: nil)
  //获取验证码
}

@objc func timerThread() {
  let timeCount = count
  for _ in 0..<timeCount {
    count = count - 1
    self.performSelector(onMainThread: #selector(updateCodeBtn), with: self, waitUntilDone: true)
    sleep(1)
  }
}

@objc func updateCodeBtn() {
  //处理更新
}

方式二:
使用Timer,在iOS10后可使用

Timer.scheduledTimer(withTimeInterval: TimeInterval(1), repeats: true, block:{
  (timer: Timer) -> Void in
})
← 返回《Mac》目录书架 →