user2074150
user2074150

Reputation:

DatePicker for UITextfield,should I use NSDatePicker?

I have a UITextfield "Birthday" and right now after clicking on the text field I have a keyboard and I would like to change it to a datepicker.

Is there anyone who can help step by step with this?what should I add to my code and what changes do I need to make.

Here is what I have for my UITextField "Birthady":

field = [[UITextField alloc] initWithFrame:frame];
[self.appDel.styleManager decorateTextField:field];
field.placeholder = @"Birthday";
[container addSubview:field];
self.registrationFormBirthday = field;
self.registrationFormBirthday.delegate = self;

Based on Jonathan answer this is what I have right now:

-(void)textFieldDidBeginEditing:(UITextField *)textField
    {
    if textField == XtextLabel
    {
    UIDatePicker *datePicker = [[UIDatePicker alloc] init];
    NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar] ;
    NSDate *currentDate = [NSDate date];
    NSDateComponents *comps = [[NSDateComponents alloc] init] ;
    [comps setYear:-0];
    NSDate *maximumDate = [calendar dateByAddingComponents:comps toDate:currentDate options:0];
    [comps setYear:-90];
    NSDate *minimumDate = [calendar dateByAddingComponents:comps toDate:currentDate options:0];
    [datePicker setMaximumDate:maximumDate];
    [datePicker setMinimumDate:minimumDate];
    datePicker.datePickerMode = UIDatePickerModeDate;
    textField.inputView = datePicker;
    }
    }

How Can I show the selected date on in the XtextLabel and exit datePicker?

Upvotes: 0

Views: 1429

Answers (1)

Bushbert
Bushbert

Reputation: 158

Something like...

UIDatePicker *datePicker = [[[UIDatePicker alloc] init]];
datePicker.datePickerMode = UIDatePickerModeDate;
[datePicker addTarget:self action:@selector(datePickerValueChanged:)      forControlEvents:UIControlEventValueChanged];
textField.inputView = datePicker;    


- (IBAction)datePickerValueChanged:(id)sender {

   NSDate *pickerDate = [sender date]; //Do something with the date
}

Upvotes: 1

Related Questions