倒数计时器未更新 .text



文本计数 这些是我喜欢倒计时的数字,S=开始,O=停止,R=重置。添加了更简单的功能,但不想使用它们。

我正在尝试在此应用程序上设置倒数计时器,但是在使其与我看到的教程一起使用时遇到问题。我的猜测是这个版本的 swift 有不同的功能,Xcode 版本 9.4。

目标是有一个一年、一天和时间的计数器,当每个用完时它会停止并计数下一个,最好我想要随机数,没有开始或停止按钮,开始可以是一旦应用程序打开或如果用户在上一个屏幕上接受。

我已经尝试过这些方法,但它们要么不做任何事情,要么强迫我@object使用 func counter((,我相信计时器一旦成为对象就不会调用函数,我不知道如何调用它。

import UIKit
class ViewController: UIViewController {
var seconds = 30
var timer = Timer()
//these are others I will implement later
@IBOutlet weak var YRS: UILabel!
var yrs = 1
@IBOutlet weak var DAY: UILabel!
var day = 3
@IBOutlet weak var HRS: UILabel!
var hrs = 5
@IBOutlet weak var SEC: UILabel!
var sec = 35
@IBOutlet weak var MIN: UILabel!

//timer function, I believe I have to change #selector as is not 
calling the counter func
@IBAction func str(_ sender: UIButton) {
//I have also used just counter but nothing changes :/
timer = Timer.init(timeInterval: 60.0, target: self, selector:          
#selector(ViewController.counter), userInfo: nil, repeats: true)
MIN.text = String (seconds)   
}
//stop button
@IBAction func sto(_ sender: Any) {
}
//reset button
@IBAction func rst(_ sender: Any) {
}
//counter here -1
@objc func counter(){
seconds -= 1
MIN.text = String(seconds)
if (seconds == 00) {
timer.invalidate()
}
}

override func viewDidLoad() {
super.viewDidLoad()    
}

//Something I have tried but did not work
_ = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(UIMenuController.update), userInfo: nil, repeats: true)
}

func update() {
if(min > 0) {
MIN.text = String(min-1)
}
}
//No errors found, the screen is updated with the value but it does not change.

这是操场上的一个测试。但是你当然也可以在你的viewDidLoad Method中使用它。它还没有准备好,你只需要在我注释它的地方添加代码(在这里添加代码......我将计时器设置为 0.1 秒,以便我可以对其进行测试。

var YRS = UILabel()
var yrs = 1
var DAY = UILabel()
var day = 3
var HRS = UILabel()
var hrs = 5
var SEC = UILabel()
var sec = 35
var MIN = UILabel()
var min = 15
YRS.text = "years (yrs)"
YRS.sizeToFit()
view.addSubview(YRS)
DAY.text = "day (day)"
DAY.sizeToFit()
DAY.frame.origin.y = 30
view.addSubview(DAY)
HRS.text = "HRS (hrs)"
HRS.sizeToFit()
HRS.frame.origin.y = 60
view.addSubview(HRS)
MIN.text = "min (day)"
MIN.sizeToFit()
MIN.frame.origin.y = 90
view.addSubview(MIN)
SEC.text = "SEC (sec)"
SEC.sizeToFit()
SEC.frame.origin.y = 120
view.addSubview(SEC)
Timer.scheduledTimer(withTimeInterval: 0.1, repeats: true) { (timer) in
sec = sec - 1
if sec < 0 { sec = 59
min = min - 1
if min < 0 { min = 59
hrs = hrs - 1
if hrs < 0 {
hrs = 23
HRS.text = "HRS (hrs)"
HRS.sizeToFit() 
// add code here for day ...
}
}
MIN.text = "min (min)"
MIN.sizeToFit()
}
SEC.text = "sec (sec)"
SEC.sizeToFit()
}

最新更新