我试图在我的Datepicker中设置最大和最小小时。我设法设置最小值,但无法解决最大值。以下是我到目前为止的情况:
let startHour: Int = 8
let endHour: Int = 22
let date1: NSDate = NSDate()
let gregorian: NSCalendar = NSCalendar(calendarIdentifier: NSCalendarIdentifierGregorian)!
let components: NSDateComponents = gregorian.components(([.Day, .Month, .Year, .Hour, .Minute]), fromDate: date1)
if components.hour >= 22 && components.hour < 8 {
components.hour = startHour
components.minute = 0
components.second = 0
}
let startDate: NSDate = gregorian.dateFromComponents(components)!
components.hour = endHour
components.minute = 0
let endDate: NSDate = gregorian.dateFromComponents(components)!
picker.datePickerMode = .DateAndTime
picker.minimumDate = startDate
picker.maximumDate = endDate
picker.setDate(startDate, animated: true)
有没有办法忽略方法.maximumDate(现在是我当前的日期)中的当前日期和月份?它将我选择的未来日期设置回当前日期,并仅检查设置为上午8点至晚上10点的小时间隔。我希望DatePicker能够为每个未来日的上午8点到晚上10点开始提取时间,而不仅仅是当天。
答案 0 :(得分:2)
删除picker.maximumDate = endDate
并编写自己的自定义验证方法。
// Call datePickerChanged method when the picker finishes rotating
picker.addTarget(self, action: #selector(datePickerChanged(_:)), forControlEvents: .ValueChanged)
func datePickerChanged(picker: UIDatePicker) {
let selectedDate = picker.date
// 1) if selectedDate's hour > than your endHour (10pm)
// 2) create yourNewDate with endHour = 10pm
// 3) set new date with animation
picker.setDate(yourNewDate, animated: true)
}