我正在尝试制作一个非常简单的倒计时计时器,该计时器在屏幕上显示,而无需按下开始按钮;连续的但是,当我运行模拟器时,屏幕上仅显示“ Label”,没有倒数计时。我的插座正确连接,没有出现任何错误,即使按照指南进行操作,我也无法弄清楚自己在做什么。有任何简单的解决方案吗?
代码:
class ViewController: UIViewController {
@IBOutlet weak var timerLabel: UILabel!
var seconds = 15
var timer = Timer()
func runTimer() {
timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: Selector(("updateTimer")),userInfo: nil, repeats: true)
}
func updateTimer() {
seconds -= 1
timerLabel.text = String(seconds)
}
override func viewDidLoad() {
super.viewDidLoad()
runTimer()
// Do any additional setup after loading the view, typically from a nib.
}
}
答案 0 :(得分:1)
只需在以下时间启动计时器
:func viewDidAppear() {
super.viewDidAppear()
self.runTimer()
}
并将其停止在:
func viewDidDisappear() {
super.viewDidDisappear()
self.timer?.invalidate()
self.timer = nil
}
答案 1 :(得分:1)
首先在此行更改selector
语法:
func runTimer() {
timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(updateTimer),userInfo: nil, repeats: true)
}
并将@objc
添加到该功能中:
@objc func updateTimer() {
seconds -= 1
timerLabel.text = String(seconds)
}