swift3.0 定时器 显示时间

作者: iOS_Developer | 来源:发表于2017-04-26 15:42 被阅读1170次

1.需求.在view上展示一个label,用来显示当前时间并走秒
2.思路.有两个方法,一个是用Timer,创建一个定时器,用Date获取当前时间,代码如下
第一个方法:
在viewcontroller中定义变量

    private var timer : Timer?
    private var timeLb : UILabel?

在viewdidload中创建timeLb并加入view,创建Date对象

timeLb = UILabel.init(frame: CGRect(x: (kScreenWidth - 10) * 0.5 + 10, y: kScreenHeight * 0.5, width: (kScreenWidth - 10) * 0.5, height: 20))
        
        timeLb?.text = "09:09:45"
        
        timeLb?.textColor = RGBCOLOR(r: 66, 176, 216)
        
        timeLb?.textAlignment = NSTextAlignment.left
        
        view.addSubview(timeLb!)

        let currentDate = Date(timeIntervalSinceNow: 1)
                
        let dateFormatter = DateFormatter()
        
        dateFormatter.dateFormat = "HH:mm:ss"

        timeLb?.text = dateFormatter.string(from: currentDate)
        
        addCycleTimer()
// 添加定时器
    fileprivate func addCycleTimer() {
        timer = Timer(timeInterval: 1.0, target: self, selector: #selector(self.handleTimer), userInfo: nil, repeats: true)
        RunLoop.main.add(timer!, forMode:RunLoopMode.commonModes)
    }
    
    @objc private func handleTimer (){
        
        let currentDate = Date(timeIntervalSinceNow: 1)
        
        //        let currentDate = Date()
        
        let dateFormatter = DateFormatter()
        
        dateFormatter.dateFormat = "HH:mm:ss"
        
        timeLb?.text = dateFormatter.string(from: currentDate)
    

第二个方法是用DispatchSourceTimer在子线程实现,代码如下

//
//  ViewController.swift

import UIKit

class ViewController: UIViewController {

  private var timeLb : UILabel?
  var codeTimer: DispatchSourceTimer?


  override func viewDidLoad() {
      super.viewDidLoad()

      timeLb = UILabel.init(frame: CGRect(x: (UIScreen.main.bounds.size.width - 10) * 0.5 + 10, y: UIScreen.main.bounds.size.height * 0.5, width: (UIScreen.main.bounds.size.width - 10) * 0.5, height: 20))

      timeLb?.text = ""
      
      timeLb?.textAlignment = NSTextAlignment.left
      
      view.addSubview(timeLb!)
      
      // 定义需要计时的时间
      var timeCount = 60
      // 在global线程里创建一个时间源
      codeTimer = DispatchSource.makeTimerSource(queue:      DispatchQueue.global())
      // 设定这个时间源是每秒循环一次,立即开始
      codeTimer?.scheduleRepeating(deadline: .now(), interval: .seconds(1))
      // 设定时间源的触发事件
      codeTimer?.setEventHandler(handler: {
          // 每秒计时一次
          timeCount = timeCount - 1
          
          let currentDate = Date(timeIntervalSinceNow: 1)
//            let currentDate = Date()
          
          //        let currentDate = Date()
          
          let dateFormatter = DateFormatter()
          
          dateFormatter.dateFormat = "HH:mm:ss"
          
          // 返回主线程处理一些事件,更新UI等等
          DispatchQueue.main.async {
              self.timeLb?.text = dateFormatter.string(from: currentDate)
          }
      })
      // 启动时间源
      codeTimer?.resume()
  }
  override func viewWillDisappear(_ animated: Bool) {
      super.viewWillDisappear(animated)
      codeTimer?.cancel()
  }
  override func didReceiveMemoryWarning() {
      super.didReceiveMemoryWarning()
      // Dispose of any resources that can be recreated.
  }

}

相关文章

  • swift3.0 定时器 显示时间

    1.需求.在view上展示一个label,用来显示当前时间并走秒2.思路.有两个方法,一个是用Timer,创建一个...

  • Swift3.0之后GCD定时器如何创建

    Swift3.0很多语法都有变化,GCD的定时器也发生了变化 1.首先,创建定时器,和之前的有所不同,代码如下: ...

  • Swift3.0中GCD定时器的使用

    swift3.0语法变化之后,好多东西用法都发生了变化,最近要用到定时器,网上搜集了好多写法,最后才搞好,现分享一...

  • Swift3.0

    swift3.0变化 swift3.0已近发布了一段时间,在AlamoFire swift3.0版本重新支持iOS...

  • ios开发小技巧总结(一)

    1.设置标签的文字显示不同颜色。 2.定时器的取消,关闭,重启(1).设置定时器。 (2).定时器关闭 [_t...

  • CADisplaylink跑马灯

    CADisplayLink 是一个用于显示的定时器,以屏幕刷新频率同步绘图 用UILabel举例: 创建定时器: ...

  • 蜂鸣器

    version2 显示函数做了略微的修改 定时器模拟门铃

  • 页面延时返回

    使用wx.redirectTo({ })打开新 页面 定时器显示出返回图标

  • Swift3.0 - 属性

    Swift3.0 - 真的很简单Swift3.0 - 数据类型Swift3.0 - ArraySwift3.0 -...

  • Swift3.0 - 镜像

    Swift3.0 - 真的很简单Swift3.0 - 数据类型Swift3.0 - ArraySwift3.0 -...

网友评论

    本文标题:swift3.0 定时器 显示时间

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