这是我到目前为止尝试过的
@ IBOutlet弱var goOrPauseLabel:UILabel!
@IBOutlet weak var countDownLabel: UILabel!
@IBAction func startButton(_ sender: Any) {
timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(countDownMethod), userInfo: nil, repeats: true)
}
@objc func countDownMethod() {
countDownLabel.text = "\(setCountdown)"
setCountdown -= 1
if setCountdown <= 0 {
countDownLabel.text = "\(pauseCountdown)"
pauseCountdown -= 1
}
else if pauseCountdown <= 0 {
countDownLabel.text = "\(setCountdown)"
setCountdown -= 1
}
}
希望您能理解我的问题我感谢您的回答
import UIKit
import PlaygroundSupport
class CountdownTimer {
var timer: Timer?
init(_ time: Int, completion: @escaping (Int) -> Void) {
var timePeriod = time
timer = Timer.scheduledTimer(withTimeInterval: 1, repeats: true) { _ in
timePeriod -= 1
completion(timePeriod)
if timePeriod == 0 {
self.timer?.invalidate()
}
}
}
}
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let label = UILabel()
label.text = "5"
label.textColor = .white
label.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(label)
NSLayoutConstraint.activate([
label.centerXAnchor.constraint(equalTo: view.centerXAnchor),
label.centerYAnchor.constraint(equalTo: view.centerYAnchor)])
CountdownTimer(5) { time in
label.text = "\(time)"
}
}
}
PlaygroundPage.current.liveView = ViewController()
PlaygroundPage.current.needsIndefiniteExecution = true