Text to count这些是我想倒数的数字,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.
答案 0 :(得分:0)
这是在Playground中进行的测试。但是您当然也可以在viewDidLoad方法中使用它。还没有准备好,您只需要在我评论的位置添加代码(在此处添加代码...)。我将计时器设置为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()
}