Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
885 views
in Technique[技术] by (71.8m points)

ios - UIDatePicker restrict hours but not date

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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]];
    }
}

Edit: 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"


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...