Swift 从日期选择器开始的倒计时天数

Swift CountDown Days Until from Date Picker

我一直在努力在 Swift 中进行倒计时,它只显示距离输入为 DatePicker 的某个日期还剩多少天...我有 Swift 的 creo 经验,所以,我已经挣扎了一段时间。我在这里尝试了一些类似的答案但没有奏效,我看了一个教程但是是一个正常的倒计时,有月、日、分钟和秒,这是代码。

import UIKit

class ViewController: UIViewController {

@IBOutlet weak var timeLabel: UILabel!

let formatter = DateFormatter()
let userCleander = Calendar.current;
let requestedComponent : Set<Calendar.Component> = [
    Calendar.Component.month,
    Calendar.Component.day
]

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.

    let timer = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(timePrinter), userInfo: nil, repeats: true)

    timer.fire()
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

func timeCalculator(dateFormat: String, endTime: String, startTime: Date = Date()) -> DateComponents {
    formatter.dateFormat = dateFormat
    let _startTime = startTime
    let _endTime = formatter.date(from: endTime)

    let timeDifference = userCleander.dateComponents(requestedComponent, from: _startTime, to: _endTime!)
    return timeDifference
}

func timePrinter() -> Void {
    let time = timeCalculator(dateFormat: "MM/dd/yyyy a", endTime: "12/25/2018 a")
    timeLabel.text = "\(time.month!) Months \(time.day!) Days"
}

}

几件事:不要使用字符串来比较日期。使用日期对象和日历操作。 (稍后会详细介绍。)

不要 运行 计时器每秒一次。将当前日期保存为用户默认值。当您的应用程序启动时,将保存的日期与当前日期进行比较,看看日期是否发生了变化。

在 运行ning 时,收听 UIApplicationSignificantTimeChange 通知,收到通知后,检查日期是否已更改。

至于将当前日期与 user-selected 日期进行比较,您使用 dateComponents(_:from:to:) 的想法是正确的,但您应该只传入 [.day].[= 的组成部分14=]

编辑:

这样的代码就可以解决问题:

override func viewDidLoad() {
    super.viewDidLoad()
    //Set up the date picker to pick dates, not dates & times
    datePicker.datePickerMode =  .date
    
    //Force the date picker to use midnight today as it's base date and
    //to pick a date at least 1 day in the future
    guard let today = Calendar.current.date(bySettingHour: 0, minute: 0, second: 0, of: Date()),
        let tomorrow = Calendar.current.date(byAdding: .day, value: 1, to: today)
        else {
            return
    }
    datePicker.minimumDate = tomorrow
    datePicker.date = tomorrow
}

@IBAction func datePickerChanged(_ sender: UIDatePicker) {
    let future = datePicker.date
    //Use midnight today as the starting date
    guard let today = Calendar.current.date(bySettingHour: 0, minute: 0, second: 0, of: Date()) else { return }
    
    //Calculate the number of days between today and the user's chosen day.
    let difference = Calendar.current.dateComponents([.day], from: today, to: future)
    guard let days = difference.day else { return }
    let ess = days > 1 ? "s" : ""
    infoLabel.text = "That date is \(days) day\(ess) away."
}