Show datepicker on textfield tap

lolol picture lolol · Oct 10, 2012 · Viewed 45.8k times · Source

I'm very new to iOS so obviously I'm missing a few concepts when trying to follow this solution Display datepicker on tapping on textfield to my problem.

I have the interface and implementation in a class called DatepickerAppDelegate, but I'm lost here:

"In the XIB, Pull out a UIToolbar and a UIDatePicker but don't attach it to the view. Connect the outlets appropriately. dateChanged: responds to changes in the date picker and doneEditing: is called when the Done button in the tool bar is clicked. Connect them too. The methods are implemented as listed below."

I read something about XIB's but I'm using a storyboard, so I think I don't have then. Also, I'm not sure how I'm supposed to pull out elements without attaching it to my view controllers (I'm trying, but when I release the mouse button, the tool flies back to the toolbar), and I don't even understand why I need a UIToolbar.

And finally, how do I connect my textfield to the datepicker delegate?

Can someone help me?

UPDATE:

In fact it is very simple, I just need to:

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

self.birthday.inputView = datePicker;

Answer

Dave DeLong picture Dave DeLong · Oct 17, 2012

UIResponder, from which UITextField inherits, defines a property called inputView. This property (a UIView *) can define a view that will be displayed instead of the keyboard when that UIResponder becomes the first responder.

Thus, if you want a UIDatePicker to appear when you tap in a textField (ie, you make that textField the first responder), then you can say, naïvely:

UIDatePicker *datePicker = [[UIDatePicker alloc] init...];
... configure datePicker ...

[myTextField setInputView:datePicker];

Now, when your UITextField is tapped, a UIDatePicker will be brought up instead.

HOWEVER

You'll want to do more than this, because you'll need to handle different orientations and different idioms.

But that's the basic idea.

(And if you want a toolbar above the UIDatePicker, that's what the inputAccessoryView property is for...)