指定标签不显示倒计时

Designated label not displaying countdown

我实施了倒计时,但目前指定用于显示该值的标签根本不显示该值。我试过 print(countdownLabel) 看看它是否正在记录返回标签的属性而不是倒计时。提前致谢!

class CountdownViewController: UIViewController {

    @IBOutlet weak var iconImage: UIImageView!
    @IBOutlet weak var countdownLabel: UILabel!

    //Countdown
    let futureDate: Date = {
        let future = DateComponents(
            year: 2021,
            month: 1,
            day: 06,
            hour: 09,
            minute: 32 ,
            second: 45
        )
        return Calendar.current.date(from: future)!

    }()

    var countdown: DateComponents {
        return Calendar.current.dateComponents([.day, .hour, .minute, .second], from: Date(), to: futureDate)
    }

    @objc func updateTime() {
        let countdown = self.countdown //only compute once per call
        let days = countdown.day!
        let hours = countdown.hour!
        let minutes = countdown.minute!
        let seconds = countdown.second!
        self.countdownLabel.text = String(format: "%02d:%02d:%02d:%02d", days, hours, minutes, seconds)
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        func runCountdown() {
            Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(updateTime), userInfo: nil, repeats: true)
        }
        runCountdown()
        (print(countdown))
        (print(countdownLabel as Any))
    }
}

您的代码中的问题是,您在另一个函数 viewDidLoad() 中声明了函数 runCountdown(),但是之后您没有调用 runCountdown()

override func viewDidLoad() {
    super.viewDidLoad()
    func runCountdown() {
        Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(updateTime), userInfo: nil, repeats: true)
    }
    runCountdown()
    (print(countdown))
    (print(countdownLabel as Any))
}