Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to block days in UIDatePicker for iOS

I'm using a Date picker on my IOS app, and I want to know if is possible to block some days. For example, I need to block all mondays from a year, is this possible?

Thanks.

like image 298
Pach Avatar asked Aug 30 '12 22:08

Pach


2 Answers

The only thing you can do is add a custom UIPickerView as described in the comments or implement a method that is called for the event UIControlEventValueChanged as described here

then check the new value for a valid weekday. you can get the weekday with:

NSCalendar* calendar = [NSCalendar currentCalendar];
NSDateComponents* components = [calendar components:NSWeekdayCalendarUnit fromDate:[NSDate date]];
return [components weekday]; // 1 = Sunday, 2 = Monday, ...

There is no way to hide some days in the scrollwheel.

like image 61
E. Lüders Avatar answered Oct 24 '22 16:10

E. Lüders


Here is the Swift 4 answer to this question (original answer by Nicholas Harlen):

let datePicker: UIDatePicker = UIDatePicker(frame: .zero)
    datePicker.datePickerMode = .date
    datePicker.addTarget(self, action: #selector(datePickerValueChanged(_:)), for: .valueChanged)

@objc func datePickerValueChanged(_ sender: UIDatePicker) {
    let calender: Calendar = Calendar(identifier: .gregorian)
    let weekday = calender.component(.weekday, from: sender.date)
    //sunday
    if weekday == 1 {
        datePicker.setDate(Date(timeInterval: 60*60*24*1, since: sender.date), animated: true)
    } else if weekday == 7 {
        datePicker.setDate(Date(timeInterval: 60*60*24*(-1), since: sender.date), animated: true)
    }
}
like image 30
iCappsCVA Avatar answered Oct 24 '22 17:10

iCappsCVA