The date picker is used to pick date for textfield. It is placed in textFieldDidBeginEditing (a delegate method of UITextField), so that the keyboard is replaced with date picker as soon as you enter into textfield. updateTextField will set the value of textfield equal to chosen date.
Code:
-(void)textFieldDidBeginEditing:(UITextField *)textField
{ if(textField.tag==111) //tag for mytextField- to set date picker for desired textfield
UIDatePicker *datePicker = [[UIDatePicker alloc]init];
datePicker.datePickerMode = UIDatePickerModeDate;
[datePicker setDate:[NSDate date]];
[datePicker addTarget:self action:@selector(updateTextField:) forControlEvents:UIControlEventValueChanged];
[mytextField setInputView:datePicker]; //mytextField is the field you want to set as date
}
}
-(void)updateTextField :(UIDatePicker *)datePicker{
NSDate *pickerDate = [datePicker date];
NSString *selectionString = [[NSString alloc]
initWithFormat:@"%@",
[pickerDate descriptionWithLocale: nil]];
mytextField.text = selectionString;
NSDateFormatter* dateFormatter = [[NSDateFormatter alloc] init];
dateFormatter.dateFormat = @"dd/MM/yyyy";
mytextField.text =[dateFormatter stringFromDate:pickerDate];
}
0 Comment(s)