Replacing UITextField input with a UIDatePicker

12,096

Try this code.. here I am putting an datepicker to a uitextfield.. it will have a done button at the top right navigation bar.. so by clicking done I will user can dismiss the datepicker.. the another best method is by putting a toolbar above the datepicker having the done button.. Try this it will work.. when changing the datepicker you can populate the text field.. Hope this helps..

see this stackoverflow link https://stackoverflow.com/a/4824319/763747 this will have the datepicker with done button as toolbar above the keybord..

#pragma mark -
#pragma mark - TextField Delegate

- (BOOL)textFieldShouldReturn:(UITextField *)textField 
{
    [textField resignFirstResponder];
    return TRUE;
}


- (void) textFieldDidBeginEditing:(UITextField *)textField {
    itsRightBarButton.title  = @"Done";
    itsRightBarButton.style = UIBarButtonItemStyleDone;
    itsRightBarButton.target = self;
    itsRightBarButton.action = @selector(doneAction:);
    if ([textField isEqual:itsIncidentDateTextField])
    {
        itsDatePicker = [[[UIDatePicker alloc] init] autorelease];
        itsDatePicker.datePickerMode = UIDatePickerModeDate;
        [itsDatePicker addTarget:self action:@selector(incidentDateValueChanged:) forControlEvents:UIControlEventValueChanged];
        //datePicker.tag = indexPath.row;
        textField.inputView = itsDatePicker;
    }
}

- (IBAction) incidentDateValueChanged:(id)sender{
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"MMM d, yyyy"];
    itsIncidentDateTextField.text = [dateFormatter stringFromDate:[itsDatePicker date]];
    [dateFormatter release];
}
Share:
12,096
johnnyspo
Author by

johnnyspo

Updated on June 04, 2022

Comments

  • johnnyspo
    johnnyspo about 2 years

    I have a table view controller with (among others) a cell that is to represent a date. I followed this post "How do I make a modal date picker that only covers half the screen?" and I have it working with one big exception - I can't get the picker to disappear!

    I tried registering for the event UIControlEventTouchUpOutside, but it seems that this is not generated by the picker (or at least in the mode that I am using it).

    How can I recognize that the user has finished selecting a date?

    Also, is there a way to disable the user from inputting directly into the UITextField? I want to force them to use the picker. I saw this post "Disable blinking cursor in UITextField?", but is there another way?

    Reagards,

    --John

  • johnnyspo
    johnnyspo about 12 years
    I see that's the technique used in Contacts, say if you add a birthday. I'll have to rework my view because I currently have a "Cancel" button as the right bar button item. I'll give it a try. Thanks for the answer!
  • johnnyspo
    johnnyspo about 12 years
    Exactly what I did!! Thanks again.