1) in the .h file of your view controller, make sure you assign a text field delegate:
@interface YourViewController : UIViewController <UITextFieldDelegate>
as well as IBOutlet for the birthday text box
2) declare the date selection as a class variable to make it available from all the different methods in the class. in the .m file after import and before implementation, do the following:
@interface YourViewController () { UIDatePicker *datePicker; } @end
3) in viewdidload:
4) in the same .m file, define a selector that will update the text field every time the date selection changes:
-(void)updateTextField:(id)sender { UIDatePicker *picker = (UIDatePicker*)self.BirthdateTextfield.inputView; self.BirthdateTextfield.text = [self formatDate:picker.date]; }
5) last but not least: it is a method called before a date is set in textfield.text (textfield.text requires a string, not a date):
- (NSString *)formatDate:(NSDate *)date { NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; [dateFormatter setDateStyle:NSDateFormatterShortStyle]; [dateFormatter setDateFormat:@"dd-MMM-yyyy"]; NSString *formattedDate = [dateFormatter stringFromDate:date]; return formattedDate; }
enjoy coding!
source share