swift學習 - 計時器

swift學習之計時器

這個demo主要學習在swift中如何操做計時器(Timer),按鈕(UIButton),文本(Label)

效果圖:

代碼

import UIKit

class ViewController: UIViewController {

    var btn1:UIButton?
    var timer:Timer?
    var label:UILabel?
    var a = 0.0
    
    override func viewDidLoad() {
        super.viewDidLoad()
        setupUI()
    }
    
    func setupUI() {
        
        let button = UIButton(frame:CGRect(x: 20, y: 400, width:50, height: 50))
        button.backgroundColor = .red
        button.addTarget(self, action: #selector(startCLick(item:)), for: .touchUpInside)
        button.layer.cornerRadius = 25
        button.clipsToBounds = true
        button.setTitle("開始", for: .normal)
        btn1 = button
        view.addSubview(button)
        
        let btn = UIButton(frame:CGRect(x: 300, y: 400, width: 50, height: 50))
        btn.backgroundColor = .blue
        btn.addTarget(self, action: #selector(startCLick(item:)), for: .touchUpInside)
        btn.setTitle("暫停", for: UIControlState.normal)
        view .addSubview(btn)
        
        let lab = UILabel(frame: CGRect(x: 50, y: 50, width: view.frame.size.width - 100, height: 50))
        lab.textAlignment = .center
        lab.font = .systemFont(ofSize: 18)
        lab.backgroundColor = .red
        lab.textColor = .white
        view.addSubview(lab)
        label = lab
        lab.text = "swift stopWatch Demo"
        
    }

    func timerIntervalx() {
        a+=1;
        label?.text = "swift stopWatch Demo \(a)"
    }
    
    func startCLick(item:UIButton) {
        if item.isEqual(btn1) {
            timeStart()
        }
        else
        {
            timePause()
        }
    }
    
    func timeStart() {
        
        if !(timer != nil) {
            timer = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(timerIntervalx), userInfo: nil, repeats: true)
        }
    }
    
    func timePause() {
        timer?.invalidate()
        timer = nil
    }
    
    
}

基本控件的建立:

UIButton:

let btn = UIButton(frame:CGRect(x: 300, y: 400, width: 50, height: 50))

UILabel:

let lab = UILabel(frame: CGRect(x: 50, y: 50, width: view.frame.size.width - 100, height: 50))

Timer:

timer = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(timerIntervalx), userInfo: nil, repeats: true)

swift中方法名更加簡單,枚舉類型能夠直接使用點語法操做

.touchUpInside  .white .center
相關文章
相關標籤/搜索