我想在键盘上显示日期选择器视图。我这样做是使用UITextField扩展名。
我的代码:
extension UITextField {
//... other functions
func showDatePicker(){
let datePicker = UIDatePicker()
datePicker.datePickerMode = .date
let toolbar = UIToolbar();
toolbar.sizeToFit()
let doneButton = UIBarButtonItem(title: "Pronto", style: UIBarButtonItemStyle.plain, target: self, action: #selector(UITextField.doneDatePicker(_:)))
let spaceButton = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.flexibleSpace, target: nil, action: nil)
let cancelButton = UIBarButtonItem(title: "Cancelar", style: UIBarButtonItemStyle.plain, target: self, action: #selector(UITextField.donePicker))
toolbar.setItems([cancelButton,spaceButton,doneButton], animated: false)
self.inputAccessoryView = toolbar
self.inputView = datePicker
}
@objc func doneDatePicker(_ datePicker: UIDatePicker){
let formatter = DateFormatter()
formatter.dateFormat = "dd/MM/yyyy"
self.text = formatter.string(from: datePicker.date)
self.endEditing(true)
}
}
我的问题是当我点击“Pronto”按钮并执行函数doneDatePicker。我需要传递UIDatePicker(或只是日期)来显示文本字段上的日期但我收到此错误:
Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[UIBarButtonItem date]: unrecognized selector sent to instance 0x103488850'
我该如何解决这个问题?
答案 0 :(得分:0)
无法通过选择器传递额外参数。为什么要将日期选择器传递给
void mergeSort(Node *head) {
Node *front = NULL, *back = NULL, *fast, *slow;
if(head == NULL || head->next == NULL)
return;
...
mergeSort(front);
mergeSort(back);
head = mergeLists(front, back);
}
替换
@objc func doneDatePicker(_ datePicker: UIDatePicker)
带
let datePicker = UIDatePicker()
并将其作为单例类中的共享实例。 然后在函数内部访问datePicker。
答案 1 :(得分:0)
您应该简单地将UITextField子类化并将您的日期选择器声明为UITextField的属性,覆盖didMoveToSuperview方法并在那里进行自定义:
class DateField: UITextField {
var date: Date?
let datePicker = UIDatePicker()
let formatter = DateFormatter()
override func didMoveToSuperview() {
datePicker.datePickerMode = .date
formatter.dateStyle = .short
let toolbar = UIToolbar()
toolbar.sizeToFit()
let done = UIBarButtonItem(title: "Pronto", style: .plain, target: self, action: #selector(doneAction))
let space = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil)
let cancel = UIBarButtonItem(title: "Cancelar", style: .plain, target: self, action: #selector(cancelAction))
toolbar.setItems([cancel,space,done], animated: false)
inputAccessoryView = toolbar
inputView = datePicker
}
@objc func cancelAction(_ sender: UIBarButtonItem) {
endEditing(true)
}
@objc func doneAction(_ sender: UIBarButtonItem) {
date = datePicker.date
text = formatter.string(from: datePicker.date)
endEditing(true)
}
}