UITextfield的DatePicker,我应该使用NSDatePicker吗?

时间:2013-02-17 23:40:17

标签: iphone datepicker uitextfield

我有一个UITextfield“生日”,现在点击文本字段后我有一个键盘,我想把它改成一个日期选择器。

是否有人可以一步一步地帮助我?我应该在代码中添加什么以及我需要做出哪些更改。

以下是我对UITextField“Birthady”所拥有的内容:

field = [[UITextField alloc] initWithFrame:frame];
[self.appDel.styleManager decorateTextField:field];
field.placeholder = @"Birthday";
[container addSubview:field];
self.registrationFormBirthday = field;
self.registrationFormBirthday.delegate = self;

根据Jonathan的回答,这就是我现在所拥有的:

-(void)textFieldDidBeginEditing:(UITextField *)textField
    {
    if textField == XtextLabel
    {
    UIDatePicker *datePicker = [[UIDatePicker alloc] init];
    NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar] ;
    NSDate *currentDate = [NSDate date];
    NSDateComponents *comps = [[NSDateComponents alloc] init] ;
    [comps setYear:-0];
    NSDate *maximumDate = [calendar dateByAddingComponents:comps toDate:currentDate options:0];
    [comps setYear:-90];
    NSDate *minimumDate = [calendar dateByAddingComponents:comps toDate:currentDate options:0];
    [datePicker setMaximumDate:maximumDate];
    [datePicker setMinimumDate:minimumDate];
    datePicker.datePickerMode = UIDatePickerModeDate;
    textField.inputView = datePicker;
    }
    }

如何在XtextLabel中显示所选日期并退出datePicker?

1 个答案:

答案 0 :(得分:1)

像...一样的东西。

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


- (IBAction)datePickerValueChanged:(id)sender {

   NSDate *pickerDate = [sender date]; //Do something with the date
}