swift 在点击事件中设置后,变量“神秘地”清除

idv4meu8  于 2022-12-26  发布在  Swift
关注(0)|答案(1)|浏览(108)

我正在Swift上进行uDemy培训,我试图通过从文本框(secondsText)阅读计时器值来增强计时器应用程序。我的变量“counter”通过读入secondsText的值来设置,但当我退出startClicked函数时,“counter”值为0。

class ViewController: UIViewController {
    var counter = 0
    var timer = Timer()

    @IBOutlet weak var labelText: UILabel!
    @IBOutlet weak var secondsText: UITextField!

   @objc func timerFunction() {

      print("timerFunction: \(counter)")
      if(counter == 0) {
          timer.invalidate()
          labelText.text = "Timer Complete"
      } else
          counter = counter - 1
          print("timerFunction: \(counter)")
          labelText.text = "Time: \(counter)"
      }
   }

   @IBAction func startClicked(_ sender: Any) {
      if let counter = Int(secondsText.text) {
          print("Timer = \(counter)")
          labelText.text = "Time: \(counter)"
          print("startClicked.Timer 1: \(counter)")
          timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(timerFunction), userInfo: nil, repeats: true)

          print("startClicked.Timer 2: \(counter)")

      } else {
           print("Invalid timer value")
           labelText.text = "Time: \(counter)"
      }
      print("startClicked.Timer 3: \(counter)")
   }
}
cwtwac6a

cwtwac6a1#

线上的counter

if let counter = …

将成员变量counter隐藏在if中。应使用其他名称。
如果要保存该值,请将其赋值为self.counter

相关问题