解决方法
您可以使用UITextField的inputView属性“替换”键盘:
- (void) initializeTextFieldInputView { UIDatePicker *datePicker = [[UIDatePicker alloc] initWithFrame:CGRectZero]; datePicker.datePickerMode = UIDatePickerModeDate; [datePicker addTarget:self action:@selector(dateUpdated:) forControlEvents:UIControlEventValueChanged]; self.textField.inputView = datePicker; } - (void) dateUpdated:(UIDatePicker *)datePicker { NSDateFormatter *formatter = [[NSDateFormatter alloc] init]; [formatter setDateFormat:@"yyyy-MM-dd"]; self.textField.text = [formatter stringFromDate:datePicker.date]; }
UIDatePickers没有像UIPickerViews这样的委托,所以这就是必须添加一个动作就好像它是一个UIButton的原因. :在选择器声明的末尾提供UIDatePicker,以方便获取更改日期.如果您不想在方法中发送对象,可以通过引用UITextField的inputView来获取UIDatePicker:
UIDatePicker *datePicker = (UIDatePicker *)self.textField.inputView;
最后,在使用NSDateFormatter设置格式时,最好创建一个方法来返回NSDateFormatter对象,以确保格式一致.至少,在项目中创建一个常量/宏,声明格式字符串.
编辑
正如Pavan在评论主题中所说,如果你想在键盘上方添加一个完成按钮,请使用inputAccessoryView:
UIToolbar *toolbar = [[UIToolbar alloc] init]; UIBarButtonItem *doneButton = [[UIBarButtonItem alloc] initWithTitle:@"Done" style:UIBarButtonItemStyleDone target:self action:@selector(doneButtonWasPressed:)]; UIBarButtonItem *flexibleSeparator = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil]; toolbar.items = @[flexibleSeparator,doneButton]; self.textField.inputAccessoryView = toolbar;
编辑2,SWIFT
看起来像这样答案已经过时了.使用Swift 3添加实现:
@IBOutlet weak var textField: UITextField! override func viewDidLoad() { super.viewDidLoad() self.initializeTextFieldInputView() } func initializeTextFieldInputView() { // Add date picker let datePicker = UIDatePicker() datePicker.datePickerMode = .date datePicker.addTarget(self,action: #selector(dateChanged(_:)),for: .valueChanged) self.textField.inputView = datePicker // Add toolbar with done button on the right let toolbar = UIToolbar(frame: CGRect(x: 0,y: 0,width: self.view.bounds.width,height: 1)) let flexibleSeparator = UIBarButtonItem(barButtonSystemItem: .flexibleSpace,target: nil,action: nil) let doneButton = UIBarButtonItem(barButtonSystemItem: .done,target: self,action: #selector(doneButtonPressed(_:))) toolbar.items = [flexibleSeparator,doneButton] self.textField.inputAccessoryView = toolbar } func dateChanged(_ datePicker: UIDatePicker) { let formatter = DateFormatter() formatter.dateFormat = "yyyy-MM-dd" self.textField.text = formatter.string(from: datePicker.date) }
您还可以通过在UITextField中转换inputView来获取UIDatePicker:
let datePicker = self.textField.inputView as? UIDatePicker