Search code examples
macoscocoatimeappkitnsdatepicker

AppKit: Duration Picker View


Is there any view similar to NSDatePicker for OS X, but for selecting durations (i.e. hours, minutes and seconds) rather than entire dates. A Google search didn't bring anything useful up, and I haven't yet succeeded in customizing NSDatePicker to be suitable for durations only - my attempts don't work properly with 12-hour (AM and PM) date modes and different timezones.


Solution

  • I don't think there is any ready-made solution, but it shouldn't be hard to make one of your own with 3 borderless text fields and a couple of labels with colons in them, all inside an NSBox with a stepper next to it.

    I think I found a way that works with an NSDate picker. I'm not sure why some of it works, but it seems necessary to set the locale to somewhere that uses a 24 hour clock, like Japan and set a calendar for the picker. The only "glitch" I see, is that there is a bit of a delay when typing in some 1 digit numbers (this is something Apple changed in OS X 10.5 I think to have the editor wait to see if you want to add a second digit). However, you can get it to update immediately by tabbing out of the field or clicking in another field. So here's the setup:

    self.picker.locale = [[NSLocale alloc] initWithLocaleIdentifier:@"ja_JP"];
        self.cal = [NSCalendar currentCalendar];
        self.cal.timeZone = [NSTimeZone timeZoneWithName:@"GMT"];
        self.picker.calendar = self.cal;
        self.picker.timeZone = cal.timeZone;
    

    And here is the action method for the picker:

        -(IBAction)dpClick:(NSDatePicker *)sender {
        NSDateComponents *comps = [cal components:NSHourCalendarUnit|NSMinuteCalendarUnit|NSSecondCalendarUnit fromDate:sender.objectValue];
        NSLog(@"hours=%ld  minutes=%ld  seconds=%ld",comps.hour,comps.minute,comps.second);
    }