使用计时器从uitextfield中的内容倒数

时间:2019-12-21 03:40:23

标签: swift timer uitextfield selector

下面的我的快速代码应该使用文本字段中放置的任何数字,然后将其倒数一秒钟。我不知道该如何获取文本字段中的内容并从中进行计数。不必担心确保用户在文本字段中输入数字而不是字符串。

    import UIKit

class ViewController: UIViewController {

var enterTime = UITextField()
var lblTime = UILabel()
var startBTN = UIButton()
var timer = Timer()
var counter = 33

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view.

    [enterTime,lblTime,startBTN].forEach{
        $0.backgroundColor = .systemRed
        view.addSubview($0)
        $0.translatesAutoresizingMaskIntoConstraints = false
    }

     enterTime.frame = CGRect(x: view.center.x-115, y: view.center.y-200, width: 60, height: 50)
     lblTime.frame = CGRect(x: view.center.x-115, y: view.center.y, width: 60, height: 50)
     startBTN.frame = CGRect(x: view.center.x-115, y: view.center.y+200, width: 60, height: 50)

    startBTN.addTarget(self, action: #selector(startHit), for: .touchDown)


}
@objc func startHit() {

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



}

    @objc func timerAction() {



        //This is where the user would take the time from uitextfield and causes it to count down
        enterTime.text = counter

        lblTime.text = "\(counter)"
    }
}

1 个答案:

答案 0 :(得分:0)

1)使计时器无效,并使用enterTime textField中的值启动计数器,然后在startHit函数中启动计时器。

2)在timerAction函数中,将计数器值减少1并在lblTime中进行设置。

您可能需要如下修改startHit和timerAction函数。

@objc func startHit() {
   timer.invalidate()
   if let counterText = enterTime.text, let counterValue = Int(counterText) {
      counter = counterValue
      lblTime.text = String(counter)
      timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(timerAction), userInfo: nil, repeats: true)
   }      
}

@objc func timerAction() {
   counter -= 1
   lblTime.text = String(counter)
   if ( counter == 0 ) {
      timer.invalidate()
   }
}