You can "replace" the keyboard using the inputView UITextField property:
- (void) initializeTextFieldInputView { UIDatePicker *datePicker = [[UIDatePicker alloc] initWithFrame:CGRectZero]; datePicker.datePickerMode = UIDatePickerModeDate; [datePicker addTarget:self action:@selector(dateUpdated:) forControlEvents:UIControlEventValueChanged]; self.textField.inputView = datePicker; } - (void) dateUpdated:(UIDatePicker *)datePicker { NSDateFormatter *formatter = [[NSDateFormatter alloc] init]; [formatter setDateFormat:@"yyyy-MM-dd"]; self.textField.text = [formatter stringFromDate:datePicker.date]; }
UIDatePickers does not have a delegate like UIPickerViews, so you need to add an action as if it were a UIButton. : At the end of the declaration, the selector provides the UIDatePicker as a convenience for getting the date it was changed. If you do not want to send the object in the method, you can get the UIDatePicker by specifying the input file UITextField:
UIDatePicker *datePicker = (UIDatePicker *)self.textField.inputView;
Finally, when setting up formats using NSDateFormatter, it is recommended that you use one method to return an NSDateFormatter object to ensure that the format is consistent. At the very least, create a constant / macro once in your project that declares a format string.
EDIT
As Pavan asked in the comments, if you want to add a "done" button above the keyboard, use inputAccessoryView:
UIToolbar *toolbar = [[UIToolbar alloc] init]; UIBarButtonItem *doneButton = [[UIBarButtonItem alloc] initWithTitle:@"Done" style:UIBarButtonItemStyleDone target:self action:@selector(doneButtonWasPressed:)]; UIBarButtonItem *flexibleSeparator = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil]; toolbar.items = @[flexibleSeparator, doneButton]; self.textField.inputAccessoryView = toolbar;
EDIT 2, SWIFT
This answer seems to be pretty outdated. Adding an implementation using Swift 3:
@IBOutlet weak var textField: UITextField! override func viewDidLoad() { super.viewDidLoad() self.initializeTextFieldInputView() } func initializeTextFieldInputView() {
You can also get a UIDatePicker by executing an inputView in a UITextField:
let datePicker = self.textField.inputView as? UIDatePicker
Chris
source share