如何将UIDatePicker的出生日期添加到UITextField?

Geo*_*rge 6 objective-c uitextfield date-of-birth ios

我在申请的注册屏幕上要求用户出生日期.我无法弄清楚如何UIDatePicker显示出生日期.我尝试使用以下代码,但它只显示日期和时间:

 UIDatePicker *dp = [[UIDatePicker alloc]init];
_textBirthday.inputView = dp;
Run Code Online (Sandbox Code Playgroud)

另外,我如何设置它以便它只接受在某一年后出生的用户?

car*_*196 19

1)在视图控制器的.h文件中,确保指定textfield委托:

@interface YourViewController : UIViewController <UITextFieldDelegate>
Run Code Online (Sandbox Code Playgroud)

并且还有生日文本字段的IBOutlet

2)将日期选择器声明为类变量,以使其可以从类中的所有不同方法访问.在.m文件中,在导入之后和实现之前执行以下操作:

@interface YourViewController () {
UIDatePicker *datePicker;
}
@end
Run Code Online (Sandbox Code Playgroud)

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];
Run Code Online (Sandbox Code Playgroud)

4)在同一个.m文件中,定义每次日期选择器更改时将更新文本字段的选择器:

-(void)updateTextField:(id)sender {
    UIDatePicker *picker = (UIDatePicker*)self.BirthdateTextfield.inputView;
    self.BirthdateTextfield.text = [self formatDate:picker.date];
}
Run Code Online (Sandbox Code Playgroud)

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;
}
Run Code Online (Sandbox Code Playgroud)

喜欢编码!