Publishers of technology books, eBooks, and videos for creative people

Home > Articles > Apple > Operating Systems

  • Print
  • + Share This
This chapter is from the book

Step 6: Implement and Validate the Date Picker

A Cocoa date picker control serves two useful purposes in the Vermont Recipes application.

First, the date picker acts as a more discriminating goTo control than the four navigation buttons. The navigation buttons are limited to the first, last, previous, and next entries. Even the most experienced chef will quickly generate more diary entries than that. Since each entry is titled with the date when it was created, a date picker is a perfect control to navigate to a specific entry. In this step, you code the date picker to navigate to the first, or oldest, entry that is equal to or more recent than the date entered in the date picker. In other words, the date picker's setting defines the oldest entry that the user wants to select. In the special case where there is no entry more recent than the date picker's setting, it navigates to the most recent entry in the diary.

Second, the date picker acts as a title for the current entry, so the user can see at a glance which entry is currently active even if its title has scrolled off the top of the window. It is updated automatically, as the user navigates through the diary, to display the date of the current entry. It should do this only when the user is not using the date picker itself to navigate. When the date picker is in use, it shows the date being set by the user. It reverts to displaying the current entry's date when the user returns keyboard focus to the text view.

When the date picker is not in use and there is no current entry—that is, when the text view is empty or the insertion point is in an untitled preface—the date picker defaults to displaying the current date.

Implement the date picker's action method first, and then turn to its role as title for the current diary entry.

  1. Cocoa's NSDatePicker class inherits from NSControl, so it responds to NSControl's -action method. Start by implementing a -goToDatedEntry: action method, on the model of the other goTo methods. It will have to call a new range method, which you will write shortly.

    In the DiaryWindowController.h header file, declare the action method after the last of the other goTo action methods:

    - (IBAction)goToDatedEntry:(id)sender;

    In the DiaryWindowController.m source file, define it like this after the last goTo... method:

    - (IBAction)goToDatedEntry:(id)sender {
         NSTextView *keyView = [self keyDiaryView];
         NSRange targetRange =
                [self firstEntryTitleRangeAtOrAfterDate:[sender dateValue]];
         if (targetRange.location != NSNotFound) {
             [keyView scrollRangeToVisible:targetRange];
             [keyView setSelectedRange:targetRange];
         }
    }

    Only two features distinguish this from the other goTo action methods: It calls a different range method, -firstEntryTitleRangeAtOrAfterDate:, which you have yet to write, and it does not return keyboard focus to the text view.

    The latter point is important for usability. The date picker should remain in control until the user explicitly clicks in the text view. This allows the user to continue changing the settings on the date picker without interruption.

  2. Write the -firstEntryTitleRangeAtOrAfterDate: range method. Like the other range methods, it belongs in DiaryDocument.

    In the DiaryDocument.h header file, declare it following -nextEntryTitleRangeForIndex: as follows:

    - (NSRange)firstEntryTitleRangeAtOrAfterDate:(NSDate *)date;

    In the DiaryDocument.m implementation file, declare it in the same relative location, like this:

    - (NSRange)firstEntryTitleRangeAtOrAfterDate:(NSDate *)targetDate {
         NSDate *date;
         NSRange tempRange;
         NSRange returnRange = [self firstEntryTitleRange];
         if (returnRange.location == NSNotFound)
                return NSMakeRange(NSNotFound, 0);
         do {
             date = [self dateFromEntryTitleRange:returnRange];
             tempRange = [self nextEntryTitleRangeForIndex:
                     returnRange.location + returnRange.length];
             if (tempRange.location == NSNotFound) break;
             if ((date == nil)
                     || ([date timeIntervalSinceDate:targetDate] < 0))
                     returnRange = tempRange;
         } while ((date == nil)
                || ([date timeIntervalSinceDate:targetDate] < 0));
         return returnRange;
    }

    The method starts by declaring the date, tempRange, and returnRange local variables. It calls -firstEntryTitleRange to set returnRange to the first entry title in the diary, returning a range with location NSNotFound if the diary contains no entries. It then enters the loop, calling -nextEntryTitleRangeForIndex: to look for each successive entry title until it runs out of titles or finds one that is more recent than the target date. It calls a method that you have yet to write, -dateFromEntryTitleRange:, to convert each title to an NSDate object if possible. It ignores entry titles that are malformed, indicated by a nil date. When it runs out of entry titles or finds one that is more recent than the target date, it returns the range with the last qualifying date.

  3. Write the -dateFromEntryTitleRange: method. Once you've done this, the support methods for the -goToDatedEntry: action method will be complete.

    In the DiaryDocument.h header file, declare it immediately following the -firstEntryTitleRangeAtOrAfterDate: method:

    - (NSDate *)dateFromEntryTitleRange:(NSRange)range;

    Define it as follows in the same relative location in the DiaryDocument.m implementation file:

    - (NSDate *)dateFromEntryTitleRange:(NSRange)range {
         if ((range.location == NSNotFound)
                || (range.length < 2)) return nil;
         range.location += 2;
         range.length -= 2;
         NSString *dateString = [[[[self diaryView] textStorage]
                string] substringWithRange:range];
                NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
                [formatter setDateStyle:NSDateFormatterLongStyle];
                [formatter setTimeStyle:NSDateFormatterLongStyle];
                NSDate *date = [formatter dateFromString:dateString];
                [formatter release];
                return date;
    }

    This method returns a date derived from the title range in the range parameter. It returns nil if the incoming range value is an NSNotFound range, or if its length is less than 2. The length test is based on the fact that all entry titles begin with the entry marker character and a space; without those, the title can't hold a date. The test is necessary so that the immediately following range manipulations do not cause an error if the user has deleted all of the title string except the initial title marker.

    The method then adjusts the incoming range to eliminate from consideration the leading title marker and space.

    The rest of the title should be a human-readable date string using NSDateFormatter's NSDateFormatterLongStyle, but the user might have edited it so that it no longer represents a date that Cocoa can interpret. Fortunately, NSDateFormatter's -dateFromString: method returns nil if it is unable to read the string. After allocating and initializing a new formatter and setting its date and time styles, the method calls -dateFromString:, releases the formatter, and returns the date as an NSDate object.

  4. The -goToDatedEntry: action method will now work, once you connect it up in Interface Builder. However, you should take steps to disable the date picker when there are no entries in the diary. First, add this clause at the end of the -validateUserInterfaceItem: implementation in the DiaryWindowController.m source file:

    } else if (action == @selector(goToDatedEntry:)) {
         return [[self document] firstEntryTitleRange].location != NSNotFound;
    }

    You call the existing -firstEntryTitleRange method for the test range because if there is no first entry, there is no entry at all.

    Next, declare a subclass of NSDatePicker called ValidatedDiaryDatePicker. This should be the same as the ValidatedDiaryButton subclass at the end of the DiaryWindowController files except that it inherits from NSDatePicker, not from NSButton. Declare it like this:

    @interface ValidatedDiaryDatePicker :
           NSDatePicker <VRValidatedControl> {
    @end

    Implement it exactly the same as the ValidatedDiaryButton's -validate method:

    @implementation ValidatedDiaryDatePicker
    
    - (void)validate {
         id validator =
                [NSApp targetForAction:[self action]
                to:[self target] from:self];
         if ((validator == nil)
                || ![validator respondsToSelector:[self action]]) {
              [self setEnabled:NO];
         } else if ([validator respondsToSelector:
                @selector(validateControl:)]) {
              [self setEnabled:[validator validateControl:self]];
         } else if ([validator respondsToSelector:
                @selector(validateUserInterfaceItem:)]) {
              [self setEnabled:[validator validateUserInterfaceItem:self]];
         } else {
              [self setEnabled:YES];
         }
    }
    
    @end

    You must also turn the date picker into a ValidatedDiaryDatePicker. Select the date picker in the diary window in Interface Builder, and then in the Validated Diary Date Picker identity inspector, choose ValidatedDiaryDatePicker as its class.

  5. The second task in this step is to tell the date picker what date to display while the user is editing or navigating in the diary. To do this, you must first write an outlet for the date picker to act as the receiver for the message.

    In the DiaryWindowController.h header file, add this declaration at the end of the instance variable declarations between the braces of the @interface directive:

    IBOutlet NSDatePicker *datePicker;

    Add this accessor method after the -otherDiaryView accessor:

    - (NSDatePicker *)datePicker;

    In the DiaryWindowController.m implementation file, add this implementation after the -otherDiaryView accessor:

    - (NSDatePicker *)datePicker {
         return [[datePicker retain] autorelease];
    }

    Build the project, and then, in Interface Builder, Control-drag from the File's Owner proxy to the date picker in the diary window and choose datePicker from the Outlets section of the HUD.

  6. Next, write a method to update the date picker's displayed value based on the range of the current entry's title. Call it -updateDatePickerValue. In the DiaryWindowController.h header file, add the declaration after -updateWindow, as follows:

    - (void)updateDatePickerValue;

    Define it like this:

    - (void)updateDatePickerValue {
         NSRange range = [self currentEntryTitleRangeForIndex:
                 [self insertionPointIndex]];
         if (range.location == NSNotFound) {
             [[self datePicker] setDateValue:[NSDate date]];
         } else {
             [[self datePicker] setDateValue:
                    [[self document] dateFromEntryTitleRange:range]];
         }
    }

    If there is no current entry or the insertion point is in an untitled preface, the method sets the displayed value of the date picker to the current date and time, using NSDatePicker's -setDateValue: method. This happens both when a new, empty window is opened and when the user moves the insertion point into the preface.

    If there is a current entry, the method sets the date picker to display its title in the form of a date. If the date value of the current entry's title is nil because the user has edited it, nothing happens because -setDateValue: does not do anything with a nil parameter value.

  7. Finally, call the -updateDatePickerValue method every time the window updates. Add this statement at the end of the existing -updateWindow method implementation:

    if (![[[self window] firstResponder]
           isKindOfClass:[NSDatePicker class]]) {
        [self updateDatePickerValue];
    }

    It is necessary to verify that the date picker does not currently have keyboard focus, because the date picker should not be updated automatically while the user is using it to set a date value.

  8. Open the DiaryWindow nib file in Interface Builder. Control-drag from the date picker in the diary window to the First Responder proxy in the DiaryWindow nib file's window, and then select the goToDatedEntry: action in the Received Actions section of the HUD. The date picker is now connected. Changing any of its values, such as the seconds, while the application is running executes the action method. This can have a highly interactive feeling in the date picker because, if you hold down the increment or decrement button to change the value continuously, the selection changes every time the value passes a threshold.

  9. Run the application and test the date picker. This requires patience, because it works to best advantage if a little time separates each entry. Taking your time, add three or four entries separated by at least several seconds. Then click in different entries at random, and confirm that the date picker changes to reflect the date and time of the current entry's title. Then click to select the seconds cell in the date picker, and click the increment and decrement buttons to change the time backward and forward. As you do this, watch the selection in the diary's text. It moves from title to title based on the principle that the first entry at or after the date set in the date picker is selected.

  • + Share This
  • 🔖 Save To Your Account