能否请您解决此代码?无论我选择哪个日期,都表明只剩1天了。
我尝试了许多其他代码来倒计时,但没有任何效果。
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var countLabel: UILabel!
var datePicker = UIDatePicker()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
//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" : ""
countLabel.text = "That date is \(days) day\(ess) away."
}
}
答案 0 :(得分:0)
您应该从作为参数发送给函数的datepicker中获取日期
let future = sender.date
并且您可能还需要修复日期选择器的初始化