swift 计时器timer

21 篇文章 0 订阅

效果图:
在这里插入图片描述

代码

//
//  LHTimerViewController.swift
//  safari
//
//  Created by 磊怀王 on 2019/12/4.
//  Copyright © 2019 磊怀王. All rights reserved.
//

import UIKit

class LHTimerViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        self.view.backgroundColor = UIColor.white
        self.navigationItem.title = "计时器"
        // Do any additional setup after loading the view
        
        self.createViews()
        
        self.timeMethon()
    }
    
    var labArr : [UILabel] = Array.init()
    
    fileprivate weak var _targetObj : AnyObject!
    
    func createViews() -> Void {
        var i = 1
        let midArr : [String] = ["时","分","秒"]
        let lab_w = 30
        let lab_h = 30
        let lab_y = 100
        
        while i < 10 {
            let lab : UILabel = UILabel.init()
            lab.textAlignment = NSTextAlignment.center
            if i % 3 == 0 {
                lab.frame = CGRect.init(x: 30 + (lab_w * 2 + 20) * (i / 3) + (i / 3 - 1) * (lab_w * 2 / 3 + 10), y: lab_y + (lab_h / 2 - lab_h / 2 / 2), width: lab_w * 2 / 3, height: lab_h / 2)
                lab.text = midArr[i / 3 - 1]
                lab.textColor = UIColor.purple
                lab.font = UIFont.systemFont(ofSize: 15.0)
            }else{
                lab.frame = CGRect.init(x: 30 + (lab_w + 10) * (i - 1 - (i / 3)) + (i / 3) * (lab_w * 2 / 3 + 10), y: lab_y, width: lab_w, height: lab_h)
                lab.text = "0"
                lab.textColor = UIColor.white
                lab.backgroundColor = UIColor.black
                lab.font = UIFont.systemFont(ofSize: 18.0)
                labArr.append(lab)
            }
            self.view.addSubview(lab)
            i += 1
        }
        
        let btnArr : [String] = ["开始","暂停","重置"]
        for objc in btnArr.enumerated() {
            let btn = UIButton.init(type: UIButton.ButtonType.custom)
            btn.frame = CGRect.init(x: objc.offset * (60 + 10) + 60, y: lab_y + lab_h + 10, width: 60, height: 30)
            btn.setTitle(btnArr[objc.offset], for: UIControl.State.normal)
            btn.titleLabel?.font = UIFont.systemFont(ofSize: 15)
            btn.backgroundColor = UIColor.black
            btn.setTitleColor(UIColor.white, for: UIControl.State.normal)
            self.view.addSubview(btn)
            btn.tag = 100 + objc.offset
            btn.addTarget(self, action: #selector(btnClick(_:)), for: UIControl.Event.touchUpInside)
        }
        
    }
    
    @objc func btnClick(_ btn : UIButton) -> Void {
        print("\(btn.tag)")
        switch btn.tag {
        case 100:
            print("begin")
//            self.timer?.fireDate = Date.init(timeIntervalSinceNow: 5) // 5 秒后开始执行
            
            self.timer?.fireDate = Date.distantPast
            break
        case 101:
            print("parse")
            self.timer?.fireDate = Date.distantFuture
            break
        case 102:
            print("reset")
            self.timer?.fireDate = Date.distantFuture
            second = 0
            let sixLab = labArr[5]
            let fiveLab = labArr[4]
            let fourLab = labArr[3]
            let threeLab = labArr[2]
            let secLab = labArr[1]
            let firstLab = labArr[0]
            sixLab.text = "0"
            fiveLab.text = "0"
            fourLab.text = "0"
            threeLab.text = "0"
            secLab.text = "0"
            firstLab.text = "0"
            break
        default:
            break
        }
    }
    var timer : Timer? = nil
    
    func timeMethon() -> Void {
        self.timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(timeAction(_:)), userInfo: nil, repeats: true)
        RunLoop.current.add(self.timer!, forMode: RunLoop.Mode.common)
        self.timer?.fireDate = Date.distantFuture
    }
    var second : Int = 3 * 3600  + 59 * 60 + 32
    
    @objc func timeAction(_ time : Timer) -> Void {
       
        second += 1
        let sixLab = labArr[5]
        let fiveLab = labArr[4]
        let fourLab = labArr[3]
        let threeLab = labArr[2]
        let secLab = labArr[1]
        let firstLab = labArr[0]
        
        if second >= 0 && second < 24 * 60 * 60 {
            let h = second / 3600
            secLab.text = "\(h % 10)"
            firstLab.text = "\(h / 10)"
            
            let min = second % 3600
            fourLab.text = "\(min / 60 % 10)"
            threeLab.text = "\(min / 60 / 10)"
            fiveLab.text = "\(min % 60 / 10)"
            sixLab.text = "\(min % 60 % 10)"
        }else{
            sixLab.text = "围"
            fiveLab.text = "范"
            fourLab.text = "出"
            threeLab.text = "超"
            secLab.text = "间"
            firstLab.text = "时"
            time.fireDate = Date.distantFuture
        }
    }
    
    override func viewWillAppear(_ animated: Bool) {
        self.tabBarController?.tabBar.isHidden = true
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        self.tabBarController?.tabBar.isHidden = false
    }
    
    override func didMove(toParent parent: UIViewController?) {
        if parent == nil {
            self.timer?.invalidate()
            self.timer = nil
        }
    }
    
    deinit {
        print(" LHTimerViewController被释放了")
    }
    
    

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destination.
        // Pass the selected object to the new view controller.
    }
    */

}

注意计时器的销毁以及controller 释放

这样的销毁方式,以及 target 方式会出现,app前后台切换导致的计时器不准的现象(非常明显)。 下篇博客说明一下。

我是磊怀 2849765859 是我QQ 欢迎联系我

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值