gpt4 book ai didi

ios - 如何传递日期选择器(或只是日期)以在 Swift 中的文本字段上显示日期?

转载 作者:行者123 更新时间:2023-11-28 07:56:57 33 4
gpt4 key购买 nike

我想在键盘上显示日期选择器 View 。我正在使用 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'

我该如何解决这个问题?

最佳答案

您应该简单地将 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)
}
}

关于ios - 如何传递日期选择器(或只是日期)以在 Swift 中的文本字段上显示日期?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47793834/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com