swfit-计时器

Posted sayimba

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了swfit-计时器相关的知识,希望对你有一定的参考价值。

import UIKit

class FourVC: UIViewController {

    var label:UILabel = UILabel()
    var index : Int = 1
    var timer:Timer = Timer()
    override func viewDidLoad() {
        super.viewDidLoad()

        label = UILabel.init()
        label.frame = CGRect.init(x:100,y:100,width:200 ,height:200)
        label.text = "计时器"
        label.textColor = UIColor.black
        self.view.addSubview(label)
        
        timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(createTimer), userInfo: nil, repeats: true)
        RunLoop.current.add(timer, forMode: RunLoopMode.commonModes)
        timer.fireDate = NSDate.distantFuture

        let endTimeBtn : UIButton = UIButton()
        endTimeBtn.frame = CGRect.init(x:250,y:300,width:100 ,height:50)
        endTimeBtn.backgroundColor = UIColor.cyan
        endTimeBtn.setTitle("停止计时", for: UIControlState.normal)
        endTimeBtn.titleColor(for: UIControlState.normal)
        endTimeBtn.setTitleColor(UIColor.black, for: UIControlState.normal)
        endTimeBtn.addTarget(self, action: #selector(pressBtn1), for: UIControlEvents.touchUpInside)
        self.view.addSubview(endTimeBtn)
        
        let startTimeBtn : UIButton = UIButton()
        startTimeBtn.frame = CGRect.init(x:50,y:300,width:100 ,height:50)
        startTimeBtn.backgroundColor = UIColor.cyan
        startTimeBtn.setTitle("开始计时", for: UIControlState.normal)
        startTimeBtn.titleColor(for: UIControlState.normal)
        startTimeBtn.setTitleColor(UIColor.black, for: UIControlState.normal)
        startTimeBtn.addTarget(self, action: #selector(pressBtn), for: UIControlEvents.touchUpInside)
        self.view.addSubview(startTimeBtn)

    }
    
    func pressBtn(){
        
        //开始计时,很远的过去
        timer.fireDate = NSDate.distantPast

    }
    
    func pressBtn1(){
        //关闭计时,很远的将来
        timer.fireDate = NSDate.distantFuture

    }
    func createTimer(){
        
        index += 1
        label.text = "\(index)"
        
        if index == 11 {
            //关闭计时器
            timer.fireDate = NSDate.distantFuture
            label.text = "倒计时停止\(index)"
        }
        
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
}

 

以上是关于swfit-计时器的主要内容,如果未能解决你的问题,请参考以下文章

Alamofire 4.0 和 Swfit 3 的字典

文本字段扩展不更新屏幕上的文本 (swfit4)

如何在使用片段和计时器的选项卡式活动上更新 UI

自动刷新android片段,直到满足条件

JUC并发编程 共享模式之工具 JUC CountdownLatch(倒计时锁) -- CountdownLatch应用(等待多个线程准备完毕( 可以覆盖上次的打印内)等待多个远程调用结束)(代码片段

swift 声明类型注释Swfit