Lessons learned from eaGeier #6

Creating a Date Picker

The eaGeier needs the possibility to enter a date e.g. to specify the purchase date for a voucher. Just providing a simple text field seems a little bit tedious. Thus – instead of opening a normal keyboard – the eaGeier provides a date picker, when a date field is selected, but at the same time keeps the possibility of entering a date via a hardware keyboard.

First the class handling the text fields needs to be the <UITextFieldDelegate>, and to implement the <UIPickerViewDelegate, UIPickerViewDataSource> protocols.

In textFieldDidBeginEditing: check if the currently selected field is a date field create a picker and use it to replace the standard keyboard. As the text field holds an NSString it needs to be transformed into an NSDate object and transformed back when a date in the picker changes calling the datePickerValueChanged: method. In addition I added a doneButton on top of the picker to let the user close the date picker:

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

Leave a Reply

Your email address will not be published.