我有一个如上图所示的弹出视图控制器。在viewDidLoad
中,我将选择器视图的最小日期设置为现在(Date()),在情节提要中,将间隔时间设置为15分钟。这是我使用的代码
class DateTimePickerVC: UIViewController {
@IBOutlet var dateTimePickerView: UIDatePicker!
var selectedDateAndTime : Date?
override func viewDidLoad() {
super.viewDidLoad()
// to make live update of selected date
dateTimePickerView.addTarget(self, action: #selector(DateTimePickerVC.datePickerValueChanged), for: UIControl.Event.valueChanged)
// minimum date is now
dateTimePickerView.minimumDate = Date()
// set initial value, to avoid nil value
selectedDateAndTime = dateTimePickerView.date
}
@objc func datePickerValueChanged (datePicker: UIDatePicker) {
selectedDateAndTime = datePicker.date
}
@IBAction func pickedButtonDidPressed(_ sender: Any) {
// send date 'selectedDateAndTime' to other VC
}
}
我在这里有2个问题:
说用户在16:28打开弹出的datePickerVC。我希望在该弹出窗口中显示的最小日期和时间将是“ Today 16:30”,但就我而言,是“ Today 16:15”。如何解决这个问题?
为避免selectedDateAndTime
的nil值,在viewDidLoad
中设置了selectedDateAndTime = dateTimePickerView.date
,所以我希望当用户立即点击保存按钮并发送{{1} }到其他VC,而无需滚动日期选择器,它将获得datePicker中显示的最小日期。假设用户打开了在16:08弹出的窗口,我希望所选日期是datePickerView(今天16:15)显示的最小日期和时间,但是我得到的实际日期值是(今天16:08),因为我设置了date
(现在)。如何获取datePicker视图上显示的最小日期?
答案 0 :(得分:2)
enum DateRoundingType {
case round
case ceil
case floor
}
extension Date {
func rounded(minutes: TimeInterval, rounding: DateRoundingType = .round) -> Date {
return rounded(seconds: minutes * 60, rounding: rounding)
}
func rounded(seconds: TimeInterval, rounding: DateRoundingType = .round) -> Date {
var roundedInterval: TimeInterval = 0
switch rounding {
case .round:
roundedInterval = (timeIntervalSinceReferenceDate / seconds).rounded() * seconds
case .ceil:
roundedInterval = ceil(timeIntervalSinceReferenceDate / seconds) * seconds
case .floor:
roundedInterval = floor(timeIntervalSinceReferenceDate / seconds) * seconds
}
return Date(timeIntervalSinceReferenceDate: roundedInterval)
}
}
用法:
//add below code in viewDidLoad()
let nextMinuteIntervalDate = Date().rounded(
minutes: 15,
rounding: .ceil
)
dateTimePickerView.minimumDate = nextMinuteIntervalDate
dateTimePickerView.setDate(nextMinuteIntervalDate, animated: true)
答案 1 :(得分:1)
我想您必须意识到一个事实,为什么它在时间(16:28)上显示16:15的时间在逻辑上仍小于16:30,所以我认为您不能这样做它没有任何逻辑意义
通过 minimumDate
的声明:
var minimumDate:日期? {获取设置}
由于minimumDate
具有 get 属性,您可以使用以下命令获取最短日期:
// Since it is an optional , we have to safe unwrap it
if let minimumDate = datePicker.minimumDate {
// Use your minimumDate variable here
}