我在我的应用程序的注册屏幕上请求用户的出生日期。我不知道如何显示出生日期 UIDatePicker
。我尝试使用以下代码,但它只显示日期和时间:
UIDatePicker *dp = [[UIDatePicker alloc]init];
_textBirthday.inputView = dp;
另外,我该如何设置它只接受特定年份之后出生的用户?
最佳答案
1) 在您的 View Controller 的 .h 文件中,确保您分配了文本字段委托(delegate):
@interface YourViewController : UIViewController <UITextFieldDelegate>
还有一个生日文本框的 IBOutlet
2) 将日期选择器声明为类变量,以使其可从类中的所有不同方法访问。在 .m 文件中,在导入之后和实现之前执行以下操作:
@interface YourViewController () {
UIDatePicker *datePicker;
}
@end
3) 在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) 在同一个 .m 文件中,定义每次日期选择器更改时将更新文本字段的选择器:
-(void)updateTextField:(id)sender {
UIDatePicker *picker = (UIDatePicker*)self.BirthdateTextfield.inputView;
self.BirthdateTextfield.text = [self formatDate:picker.date];
}
5) 最后但同样重要的是,这是在将日期分配给 textfield.text 之前调用的方法(textfield.text 需要一个字符串而不是日期):
- (NSString *)formatDate:(NSDate *)date {
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateStyle:NSDateFormatterShortStyle];
[dateFormatter setDateFormat:@"dd-MMM-yyyy"];
NSString *formattedDate = [dateFormatter stringFromDate:date];
return formattedDate;
}
享受编码吧!
关于ios - 如何将出生日期 UIDatePicker 添加到 UITextField?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30034951/