如何将一个 DatePicker 添加到 swift 中的三个文本字段

How to add one DatePicker to three textfields in swift

为此我需要将 DatePicker 添加到三个文本字段

我创建了一个如下所示的日期选择器

func addInputViewDatePicker(target: Any, selector: Selector) {

let screenWidth = UIScreen.main.bounds.width

//Add DatePicker as inputView
let datePicker = UIDatePicker(frame: CGRect(x: 0, y: 0, width: screenWidth, height: 216))
datePicker.datePickerMode = .date
self.inputView = datePicker

//Add Tool Bar as input AccessoryView
let toolBar = UIToolbar(frame: CGRect(x: 0, y: 0, width: screenWidth, height: 44))
let flexibleSpace = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil)
let cancelBarButton = UIBarButtonItem(title: "Cancel", style: .plain, target: self, action: #selector(cancelPressed))
let doneBarButton = UIBarButtonItem(title: "Done", style: .plain, target: target, action: selector)
toolBar.setItems([cancelBarButton, flexibleSpace, doneBarButton], animated: false)

self.inputAccessoryView = toolBar
}

@objc func cancelPressed() {
 self.resignFirstResponder()
}

并且我将日期选择器添加到 doneButtonPressed 中的三个文本字段,如下所示

    @objc func doneButtonPressed() {
    
    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = "yyyy-MM-dd"   
 
    if let  datePicker = self.fromDateTextfield.inputView as? UIDatePicker {
    
        self.fromDateTextfield.text = dateFormatter.string(from: datePicker.date)

    }
    if let  datePicker = self.toDateTextfield.inputView as? UIDatePicker {
      
        self.toDateTextfield.text = dateFormatter.string(from: datePicker.date)
    }
    if let  datePicker = self.lastbidDateTextfield.inputView as? UIDatePicker {
       
        self.lastbidDateTextfield.text = dateFormatter.string(from: datePicker.date)
    }
    
    self.lastbidDateTextfield.resignFirstResponder()
    self.toDateTextfield.resignFirstResponder()
    self.fromDateTextfield.resignFirstResponder()
 }

并且在 viewdidload 中:

override func viewDidLoad() {
    super.viewDidLoad()        
    fromDateTextfield.addInputViewDatePicker(target: self, selector: #selector(doneButtonPressed))
    toDateTextfield.addInputViewDatePicker(target: self, selector: #selector(doneButtonPressed))
    lastbidDateTextfield.addInputViewDatePicker(target: self, selector: #selector(doneButtonPressed))

 }

如果我在 fromDateTextfield 中添加日期,则使用上面的代码,然后在所有三个文本字段中添加相同的日期.. 而不会转到剩余的两个文本字段

我想向三个文本字段添加不同的日期..如何使用上面的代码做到这一点..

如果我上面的代码有误,请帮助我为三个三个文本字段提供新的正确工作代码

为每个 UIBarButtonItem 从 0 到 2

设置一个标签
func addInputViewDatePicker(target: Any, selector: Selector,tag:Int)
  .....
  doneBarButton.tag = tag
} 
@objc func doneButtonPressed(_ sender: UIBarButtonItem) {
  let dateFormatter = DateFormatter()
  dateFormatter.dateFormat = "yyyy-MM-dd"   
  let arr = [fromDateTextfield,toDateTextfield,lastbidDateTextfield]
  let current = arr[sender.tag]
  if let datePicker = current.inputView as? UIDatePicker {
    current.text = dateFormatter.string(from: datePicker.date)
    current.resignFirstResponder()
  }
}