UIDatePicker限制小时但不限制日期 [英] UIDatePicker restrict hours but not date
问题描述
我遇到了一种情况,我需要限制 UIDatePicker
的选定小时,但仍允许自由选择当天。如果您希望允许用户在设置的营业时间内选择日期/时间,这将非常有用。通过警告用户他们的选择很糟糕,我发现了一些与我想做的事情很接近的事情,但实际上没有改变选择器上的日期,所以我想分享我的解决方案Q& A风格。
I came across a situation where I needed to restrict a UIDatePicker
's selected hour, but still allow free selection of the day. This would be useful if you wanted to allow a user to select a date/time during set business hours. I found something that was close to what I was wanting to do by alerting the user that their selection was bad, but didn't actually change the date on the picker, so I wanted to share my solution Q&A-style.
推荐答案
此特定示例不允许选择上午7:00之前或下午9:59之后的时间。选择无效时间会立即将 UIDatePicker
滑回到相应光谱末端的最近有效时间(例如,选择10:02 pm会立即滑动回到晚上9:59)
This particular example will not allow selection of times before 7:00am or after 9:59pm. Selection of an "invalid" time will immediately slide the UIDatePicker
back to the closest valid time on the respective end of the spectrum (for example, selection of 10:02pm will immediately slide back to 9:59pm)
- (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]];
}
}
编辑: As @ DuncanC在评论中建议,可能应该包括对用户的反馈,例如标签只能在上午7:00到晚上9:59之间使用
As @DuncanC suggested in the comments, feedback to the user should probably be included, such as a label saying "Only times between 7:00am and 9:59pm can be used"
这篇关于UIDatePicker限制小时但不限制日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!