Swift定时器的几种实现方式

/ Mac / 没有评论 / 1528浏览

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
})