Skip to content

Instantly share code, notes, and snippets.

@mjjimenez
Created October 24, 2013 06:35
Show Gist options
  • Save mjjimenez/7132306 to your computer and use it in GitHub Desktop.
Save mjjimenez/7132306 to your computer and use it in GitHub Desktop.
Create date picker with accessory view and attach it to a uitextfield
- (void)viewDidLoad
{
UIDatePicker *datePicker = [[UIDatePicker alloc] init];
datePicker.datePickerMode = UIDatePickerModeDate;
UIToolbar *toolbar =[[UIToolbar alloc]initWithFrame:CGRectMake(0,0, self.view.frame.size.width,44)];
toolbar.barStyle =UIBarStyleDefault;
UIBarButtonItem *cancelButton = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemCancel
target:self
action:@selector(cancelButtonPressed:)];
UIBarButtonItem *flexibleSpace =[[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace
target:self
action:nil];
UIBarButtonItem *doneButton =[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemDone
target:self
action:@selector(doneButtonPressed:)];
[toolbar setItems:@[cancelButton,flexibleSpace, doneButton]];
self.birthdayDate.inputView = datePicker;
self.birthdayDate.inputAccessoryView = toolbar;
}
- (void)cancelButtonPressed:(id)sender
{
[self.view endEditing:YES];
}
- (void)doneButtonPressed:(id)sender
{
NSDate *birthdayDate = _datePicker.date;
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
dateFormatter.dateStyle = NSDateFormatterMediumStyle;
NSString *birthdayText = [dateFormatter stringFromDate:birthdayDate];
self.birthdayDate.text = birthdayText;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment