UIDatePicker 设置 UITextfield 文本

UIDatePicker to set UITextfield text

我有一个 UITextField 和一个 UIDatePicker,我想用它们来设置用户的生日。

我在 viewDidLoad:

中使用此代码
UIDatePicker *datePicker = [[UIDatePicker alloc] init];
birtdayTextField.inputView = datePicker;

但是我有两个问题。我在故事板的视图中放置了一个 UIDatePicker 。但它仍然会打开一个新的 datepicker,即使我已经将 *datepicker 连接到 UIDatePicker

而且它不会将 datepicker 中的信息添加到 textfield

输入视图不工作。你可以创建 lazy UIDatePicker:

- (UIDatePicker *)bDatePicker {
    if (!_bDatePicker) {
        _bDatePicker = [UIDatePicker new];
        _bDatePicker.datePickerMode = UIDatePickerModeDate;
        [_bDatePicker addTarget:self action:@selector(datePickerDidChangeDate:) forControlEvents:UIControlEventValueChanged];
    }
    return _bDatePicker;
}

然后像下面这样设置:

self.birtdayTextField.inputView = self.bDatePicker;

这是回调:

- (void)datePickerDidChangeDate:(UIDatePicker *)sender {
    self.birtdayTextField.text = [self.bDateFormatter stringFromDate:sender.date];
}

可能的格式化程序:

- (NSDateFormatter *)bDateFormatter {
    if (!_bDateFormatter) {
        _bDateFormatter = [NSDateFormatter new];
        _bDateFormatter.dateFormat = @"dd.MM.yyyy";
    }
    return _bDateFormatter;
}

为防止将错误数据粘贴到该文本字段,您可以使用它 delegate:

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    return textField != self.birtdayTextField;
}