我正在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)")
}
}
1条答案
按热度按时间cwtwac6a1#
线上的
counter
将成员变量
counter
隐藏在if
中。应使用其他名称。如果要保存该值,请将其赋值为
self.counter
。