if语句取决于计时器

时间:2018-04-24 04:14:24

标签: ios if-statement timer swift4

我的代码是在达到2秒时尝试停止计时器。那就是我现在所拥有的不起作用,我也不知道还能做些什么。我认为viewdidappear会起作用。我认为反制是我应该做的if声明。

import UIKit
class ViewController: UIViewController {
@IBOutlet var playbutton: UIButton!
@IBOutlet var titlelabel: UILabel!

var timer = Timer()
var counter = 0.0
var isRunning = false


override func viewDidLoad() {
    super.viewDidLoad()
    titlelabel.text = "\(counter)"
    playbutton.isEnabled = true

}
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        if counter == 1.9 {
            timer.invalidate()
        }
    }

@IBAction func btnreset(_ sender: UIButton) {
    timer.invalidate()
    titlelabel.text = "\(counter)"
    counter = 0
    playbutton.isEnabled = true

    isRunning = false
}
@IBAction func btnplay(_ sender: UIButton) {
    if !isRunning{
        timer = Timer.scheduledTimer(timeInterval: 0.1, target: self, selector: #selector(UpdateTime), userInfo: nil, repeats: true)
        playbutton.isEnabled = false
    isRunning = true
    }

}
@objc func UpdateTime(){
    counter += 0.1
    titlelabel.text = String(format: "%.1f", counter)

}}

1 个答案:

答案 0 :(得分:1)

有一些问题。

  • 将计时器声明为可选,然后您可以删除isRunning变量,如果计时器不在nil

    ,则计时器正在运行
    var timer : Timer?
    
    ...
    
    @IBAction func btnplay(_ sender: UIButton) {
        if timer == nil {
            timer = Timer.scheduledTimer(timeInterval: 0.1, target: self, selector: #selector(updateTime), userInfo: nil, repeats: true)
            playbutton.isEnabled = false
        }
    }
    
  • 必须在updateTime功能中检查计时器是否超过2秒,因为它经常被调用。 viewDidAppear只被调用一次。

  • 检查== 1.9无法可靠地运行,因为浮点值不完全是1.9
    检查是否等于或大于

    @objc func updateTime()
    {
        counter += 0.1
        titlelabel.text = String(format: "%.1f", counter)
        if counter >= 1.9 {
            timer?.invalidate()
            timer = nil
        }
    }
    
  • btnreset中检查计时器是否正在运行并将其重置为nil

    @IBAction func btnreset(_ sender: UIButton) {
        if timer != nil {
            timer!.invalidate()
            timer = nil
            titlelabel.text = "\(counter)"
            counter = 0
            playbutton.isEnabled = true
        }
    }
    
相关问题