我遇到的情况是我需要限制UIDatePicker
的所选时间,但仍允许自由选择当天。如果您希望允许用户在设置的营业时间内选择日期/时间,这将非常有用。通过提醒用户他们的选择很糟糕,但实际上并没有改变选择器上的日期,我发现了一些与我想做的事情很接近的事情,所以我想分享我的解决方案Q& A风格。
答案 0 :(得分:5)
此特定示例不允许选择上午7:00之前或下午9:59之后的时间。选择“无效”时间会立即将UIDatePicker
滑回频谱各自的最近有效时间(例如,选择10:02 pm将立即滑回到晚上9:59)
- (void)datePickerChanged
{
NSDateComponents *components = [[NSCalendar currentCalendar] components:NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit|NSHourCalendarUnit|NSMinuteCalendarUnit fromDate:datePicker.date];
if([components hour] < 7)
{
[components setHour:7];
[components setMinute:0];
[datePicker setDate:[[NSCalendar currentCalendar] dateFromComponents:components]];
}
else if([components hour] > 21)
{
[components setHour:21];
[components setMinute:59];
[datePicker setDate:[[NSCalendar currentCalendar] dateFromComponents:components]];
}
}
编辑:正如@DuncanC在评论中建议的那样,可能应该包含对用户的反馈,例如标签上写着“只能使用上午7:00到晚上9:59之间的时间”< / p>
答案 1 :(得分:2)
在Swift2.0中:
func datePickerChanged() {
let components = NSCalendar.currentCalendar().components(
[NSCalendarUnit.Year, NSCalendarUnit.Month, NSCalendarUnit.Day, NSCalendarUnit.WeekOfYear, NSCalendarUnit.Hour, NSCalendarUnit.Minute, NSCalendarUnit.Second, NSCalendarUnit.Weekday, NSCalendarUnit.WeekdayOrdinal, NSCalendarUnit.WeekOfYear],
fromDate: datePickerInstance.date)
if components.hour < 7 {
components.hour = 7
components.minute = 0
datePickerInstance.setDate(NSCalendar.currentCalendar().dateFromComponents(components)!, animated: true)
}
else if components.hour > 21 {
components.hour = 21
components.minute = 59
datePickerInstance.setDate(NSCalendar.currentCalendar().dateFromComponents(components)!, animated: true)
}
else {
print("Everything is good.")
}
}
答案 2 :(得分:0)
在Swift 4中:
func datePickerChanged() {
var components = Calendar.current.dateComponents([.hour, .minute, .month, .year, .day], from: datePicker.date)
if components.hour! < 7 {
components.hour = 7
components.minute = 0
datePicker.setDate(Calendar.current.date(from: components)!, animated: true)
}
else if components.hour! > 21 {
components.hour = 21
components.minute = 59
datePicker.setDate(Calendar.current.date(from: components)!, animated: true)
}
else {
print("Everything is fine!")
}
}