当用户选择 UITextField 时,要显示 UIDatePicker 而不是键盘,可以通过以下步骤实现:
let datePicker = UIDatePicker()
datePicker.datePickerMode = .date
datePicker.addTarget(self, action: #selector(datePickerValueChanged), for: .valueChanged)
let inputAccessoryView = UIView()
inputAccessoryView.frame = CGRect(x: 0, y: 0, width: view.bounds.width, height: 200)
inputAccessoryView.addSubview(datePicker)
textField.inputAccessoryView = inputAccessoryView
@objc func datePickerValueChanged(sender: UIDatePicker) {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd"
textField.text = dateFormatter.string(from: sender.date)
}
inputAccessoryViewDidScroll
方法,隐藏键盘。override func inputAccessoryViewDidScroll() {
textField.resignFirstResponder()
}
这样,当用户点击 UITextField 时,会显示 UIDatePicker,而不是键盘。
领取专属 10元无门槛券
手把手带您无忧上云