1) nel file h del vostro controller della vista fare in modo di assegnare textfield delegato:
@interface YourViewController : UIViewController <UITextFieldDelegate>
e anche avere un IBOutlet del Textfield compleanno
2) dichiarare una selezione data come variabile di classe per renderlo accessibile da tutti i diversi metodi in classe. nel file .m eseguire quanto segue dopo l'importazione e prima applicazione:
@interface YourViewController() {
UIDatePicker *datePicker;
}
@end
3) in viewDidLoad:
// make the textfield its own delegate
self.BirthdateTextfield.delegate = self;
// alloc/init your date picker, and (optional) set its initial date
datePicker = [[UIDatePicker alloc]init];
[datePicker setDate:[NSDate date]]; //this returns today's date
// theMinimumDate (which signifies the oldest a person can be) and theMaximumDate (defines the youngest a person can be) are the dates you need to define according to your requirements, declare them:
// the date string for the minimum age required (change according to your needs)
NSString *maxDateString = @"01-Jan-1996";
// the date formatter used to convert string to date
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
// the specific format to use
dateFormatter.dateFormat = @"dd-MMM-yyyy";
// converting string to date
NSDate *theMaximumDate = [dateFormatter dateFromString: maxDateString];
// repeat the same logic for theMinimumDate if needed
// here you can assign the max and min dates to your datePicker
[datePicker setMaximumDate:theMaximumDate]; //the min age restriction
[datePicker setMinimumDate:theMinimumDate]; //the max age restriction (if needed, or else dont use this line)
// set the mode
[datePicker setDatePickerMode:UIDatePickerModeDate];
// update the textfield with the date everytime it changes with selector defined below
[datePicker addTarget:self action:@selector(updateTextField:) forControlEvents:UIControlEventValueChanged];
// and finally set the datePicker as the input mode of your textfield
[self.BirthdateTextfield setInputView:datePicker];
4) in stesso file .m, definire il selettore che aggiornerà textfield ogni volta le modifiche di selezione di data:
-(void)updateTextField:(id)sender {
UIDatePicker *picker = (UIDatePicker*)self.BirthdateTextfield.inputView;
self.BirthdateTextfield.text = [self formatDate:picker.date];
}
5) non da ultimo, questo è il metodo chiamato prima di assegnare la data al TextField.text (TextField.text bisogno di una stringa non una data):
- (NSString *)formatDate:(NSDate *)date {
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateStyle:NSDateFormatterShortStyle];
[dateFormatter setDateFormat:@"dd-MMM-yyyy"];
NSString *formattedDate = [dateFormatter stringFromDate:date];
return formattedDate;
}
buona lettura!
'proprietà minimumData' di' UIDatePicker'? – Larme
e cosa intendi con * mostra solo la data e l'ora *? cosa vuoi che venga visualizzato? –