How do I rewrite the UIDatePicker component?

Go To


I've noticed that the UIDatePicker doesn't work with NSHebrewCalendar in iOS 5.0 or 5.1. I've decided to try and write my own. I'm confused as to how to populate the data and how to maintain the labels for the dates in a sane and memory efficient manner.

How many rows are there actually in each component? When do the rows get "reloaded" with new labels?

I'm going to give this a shot, and I'll post as I find out, but please post if you know anything.

2012-04-04 04:06
by Moshe


First off, thanks for filing the bug about UIDatePicker and the Hebrew calendar. :)

EDIT Now that iOS 6 has been released, you'll find that UIDatePicker now works correctly with the Hebrew calendar, making the code below unnecessary. However, I'll leave it for posterity.

As you've discovered, creating a functioning date picker is a difficult problem, because there are bajillions of weird edge cases to cover. The Hebrew calendar is particularly weird in this regard, having an intercalary month (Adar I), whereas most of western civilization is used to a calendar that only adds an extra day about once every 4 years.

That being said, creating a minimal Hebrew date picker isn't too complex, assuming you're willing to forego some of the niceties that UIDatePicker offers. So let's make it simple:

@interface HPDatePicker : UIPickerView

@property (nonatomic, retain) NSDate *date;

- (void)setDate:(NSDate *)date animated:(BOOL)animated;


We're simply going to subclass UIPickerView and add support for a date property. We're going to ignore minimumDate, maximumDate, locale, calendar, timeZone, and all the other fun properties that UIDatePicker provides. This will make our job much simpler.

The implementation is going to start off with a class extension:

@interface HPDatePicker () <UIPickerViewDelegate, UIPickerViewDataSource>


Simply to hide that the HPDatePicker is its own delegate and datasource.

Next we'll define a couple of handy constants:

#define LARGE_NUMBER_OF_ROWS 10000


You can see here that we're going to hard-code the order of the calendar units. In other words, this date picker will always display things as Month-Day-Year, regardless of any customizations or locale settings that the user may have. So if you're using this in a locale where the default format would want "Day-Month-Year", then too bad. For this simple example, this will suffice.

Now we start the implementation:

@implementation HPDatePicker {
    NSCalendar *hebrewCalendar;
    NSDateFormatter *formatter;

    NSRange maxDayRange;
    NSRange maxMonthRange;

- (id)initWithFrame:(CGRect)frame
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code
        [self setDelegate:self];
        [self setDataSource:self];

        [self setShowsSelectionIndicator:YES];

        hebrewCalendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSHebrewCalendar];
        formatter = [[NSDateFormatter alloc] init];
        [formatter setCalendar:hebrewCalendar];

        maxDayRange = [hebrewCalendar maximumRangeOfUnit:NSDayCalendarUnit];
        maxMonthRange = [hebrewCalendar maximumRangeOfUnit:NSMonthCalendarUnit];

        [self setDate:[NSDate date]];
    return self;

- (void)dealloc {
    [hebrewCalendar release];
    [formatter release];
    [super dealloc];

We're overriding the designated initializer to do some setup for us. We set the delegate and datasource to be ourself, show the selection indicator, and create a hebrew calendar object. We also create an NSDateFormatter and tell it that it should format NSDates according to the hebrew calendar. We also pull out a couple of NSRange objects and cache them as ivars so we don't have to constantly be looking things up. Finally, we initialize it with the current date.

Here are the implementations of the exposed methods:

- (void)setDate:(NSDate *)date {
    [self setDate:date animated:NO];

-setDate: just forwards on to the other method

- (NSDate *)date {
    NSDateComponents *c = [self selectedDateComponents];
    return [hebrewCalendar dateFromComponents:c];

Retrieve an NSDateComponents representing whatever is selected at the moment, turn it into an NSDate, and return that.

- (void)setDate:(NSDate *)date animated:(BOOL)animated {
    NSInteger units = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit;
    NSDateComponents *components = [hebrewCalendar components:units fromDate:date];

        NSInteger yearRow = [components year] - 1;
        [self selectRow:yearRow inComponent:YEAR_COMPONENT animated:animated];

        NSInteger middle = floor([self pickerView:self numberOfRowsInComponent:MONTH_COMPONENT] / 2);
        NSInteger startOfPhase = middle - (middle % maxMonthRange.length) - maxMonthRange.location;
        NSInteger monthRow = startOfPhase + [components month];
        [self selectRow:monthRow inComponent:MONTH_COMPONENT animated:animated];

        NSInteger middle = floor([self pickerView:self numberOfRowsInComponent:DAY_COMPONENT] / 2);
        NSInteger startOfPhase = middle - (middle % maxDayRange.length) - maxDayRange.location;
        NSInteger dayRow = startOfPhase + [components day];
        [self selectRow:dayRow inComponent:DAY_COMPONENT animated:animated];

And this is where fun stuff starts happening.

First, we'll take the date we were given and ask the hebrew calendar to break it up into a date components object. If I give it an NSDate that corresponds to the gregorian date of 4 Apr 2012, then the hebrew calendar is going to give me an NSDateComponents object that corresponds to 12 Nisan 5772, which is the same day as 4 Apr 2012.

Based on this information, I figure out which row to select in each unit, and select it. The year case is simple. I simply subtract one (rows are zero-based, but years are 1-based).

For months, I pick the middle of the rows column, figure out where that sequence starts, and add the month number to it. The same with the days.

The implementations of the base <UIPickerViewDataSource> methods are fairly trivial. We're displaying 3 components, and each one has 10,000 rows.

- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView {
    return 3;

- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component {

Getting what's selected at the current moment is fairly simple. I get the selected row in each component and either add 1 (in the case of NSYearCalendarUnit), or do a little mod operation to account for the repeating nature of the other calendar units.

- (NSDateComponents *)selectedDateComponents {
    NSDateComponents *c = [[NSDateComponents alloc] init];

    [c setYear:[self selectedRowInComponent:YEAR_COMPONENT] + 1];

    NSInteger monthRow = [self selectedRowInComponent:MONTH_COMPONENT];
    [c setMonth:(monthRow % maxMonthRange.length) + maxMonthRange.location];

    NSInteger dayRow = [self selectedRowInComponent:DAY_COMPONENT];
    [c setDay:(dayRow % maxDayRange.length) + maxDayRange.location];

    return [c autorelease];

Finally, I need some strings to show in the UI:

- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component {
    NSString *format = nil;
    NSDateComponents *c = [[NSDateComponents alloc] init];

    if (component == YEAR_COMPONENT) {
        format = @"y";
        [c setYear:row+1];
        [c setMonth:1];
        [c setDay:1];        
    } else if (component == MONTH_COMPONENT) {
        format = @"MMMM";
        [c setYear:5774];
        [c setMonth:(row % maxMonthRange.length) + maxMonthRange.location];
        [c setDay:1];
    } else if (component == DAY_COMPONENT) {
        format = @"d";
        [c setYear:5774];
        [c setMonth:1];
        [c setDay:(row % maxDayRange.length) + maxDayRange.location];

    NSDate *d = [hebrewCalendar dateFromComponents:c];
    [c release];

    [formatter setDateFormat:format];

    NSString *title = [formatter stringFromDate:d];

    return title;


This is where things are a little bit more complicated. Unfortunately for us, NSDateFormatter can only format things when given an actual NSDate. I can't just say "here's a 6" and hope to get back "Adar I". Thus, I have to construct an artificial date that has the value I want in the unit I care about.

In the case of years, that's pretty simple. Just create a date components for that year on Tishri 1, and I'm good.

For months, I have to make sure that the year is a leap year. By doing so, I can guarantee that the month names will always be "Adar I" and "Adar II", regardless of whether the current year happens to be a leap year or not.

For days, I picked an arbitrary year, because every Tishri has 30 days (and no month in the Hebrew calendar has more than 30 days).

Once we've built the appropriate date components object, we can quickly turn it into an NSDate with our hebrewCalendar ivar, set the format string on the date formatter to only be producing strings for the unit we care about, and generate a string.

Assuming you've done all this correctly, you'll end up with this:

custom hebrew date picker

Some notes:

  • I've left out the implementation of -pickerView:didSelectRow:inComponent:. It's up to you to figure out how you want to notify that the selected date changed.

  • This doesn't handle graying out invalid dates. For example, you might want to consider graying out "Adar I" if the currently selected year isn't a leap year. This would require using -pickerView:viewForRow:inComponent:reusingView: instead of the titleForRow: method.

  • UIDatePicker will highlight the current date in blue. Again, you'd have to return a custom view instead of a string to do that.

  • Your date picker will have a blackish bezel, because it is a UIPickerView. Only UIDatePickers get the blueish one.

  • The components of the picker view will span its entire width. If you want things to fit more naturally, you'll have to override -pickerView:widthForComponent: to return a sane value for the appropriate component. This could involve hard coding a value or generating all the strings, sizing them each, and picking the largest one (plus some padding).

  • As noted previously, this always displays things in Month-Day-Year order. Making this dynamic to the current locale would be a little bit trickier. You'd have to get a @"d MMMM y" string localized to the current locale (hint: look at the class methods on NSDateFormatter for that), and then parse it to figure out what the order is.

2012-04-05 03:03
by Dave DeLong
This has got to be the best answer I have ever seen on stack overflow. + - Skyler Saleh 2012-04-05 03:07
This code gets even more awesome with ARC, btw. ;-) Jus' saying - Moshe 2012-04-05 03:38
@Dave DeLong is my hero - Jacob Relkin 2012-04-05 07:27
This works a charm, Dave. Thanks so much - Moshe 2012-04-09 03:33


I assume you're using a UIPickerView?

UIPickerView works like a UITableView in that you specify another class to be the dataSource/delegate, and it gets it's data by calling methods on that class (which should conform to the UIPickerViewDelegate/DataSource protocol).

So what you should do is create a new class that is a subclass of UIPickerView, then in the initWithFrame method, set it to be its own datasource/delegate and then implement the methods.

If you've not used a UITableView before, you should familiarise yourself with the datasource/delegate pattern because it's a bit tricky to get your head around, but once you understand it it's very easy to use.

If it helps, I've written a custom UIPicker for selecting countries. This works in pretty much the same way you'll want to do your class, except that I'm using an array of country names instead of dates:

With regard to the memory question, the UIPickerView only loads the labels that are visible onscreen and recycles them as they scroll off the bottom and back onto the top, calling your delegate again each time it needs to display a new row. This is very memory efficient as there will only be a few labels on screen at a time.

2012-04-04 12:55
by Nick Lockwood
There are rather more possible dates than possible countries, I think that's the real question here - how many rows do you include in your date picker - jrturton 2012-04-04 13:33
You split your picker into three columns, then put days (31 rows) months (12 rows) and years (a suitable range, typically 1900 - present). UIPickerViewDelegate has a numberofColumns callback that lets you set how many columns you want - Nick Lockwood 2012-04-04 14:12
Alternatively, if you'd rather have one column, just set a min/max date property on your custom picker and then generate a row for each date between min and max - Nick Lockwood 2012-04-04 14:13
I want to recreate the UIDatePicker, three components and all. I am familiar with UITableView patterns - Moshe 2012-04-04 14:17
So are you clear what you need to do now, or do you have more questions - Nick Lockwood 2012-04-04 14:17
@NickLockwood See Dave's answer. ;- - Moshe 2012-04-05 03:18