如何将 UIDatePicker 添加到 UIAlertController 的 textField 中?

How to add UIDatePicker into textField in UIAlertController?

我是 swift 的新人,我的第一个应用程序需要帮助。我有 UITableView 和 To Do 任务。我需要有关在 UIAlertController 的文本字段中添加 UIDatePicker 的帮助。

 override func viewDidLoad() {
    super.viewDidLoad()
    
    self.setDatePicker.addTarget(self, action: #selector(self.dateChangeEvent), for: .valueChanged)
}

@IBAction func addNewTaskButtonAction(_ sender: Any) {
    
    let toDoAlert = UIAlertController(title: "Add ToDo", message: "Add a new task", preferredStyle: .alert)
    toDoAlert.addTextField()
    
    toDoAlert.addTextField { textField in
       textField.inputView = self.setDatePicker
        
       let toolBar = UIToolbar()
       toolBar.barStyle = .default
       toolBar.isTranslucent = true
       toolBar.isUserInteractionEnabled = true
       toolBar.sizeToFit()
        
       let doneButton = UIBarButtonItem(title: "Done", style: .done, target: self, action: #selector(self.onClickDoneButton))
        toolBar.setItems([doneButton], animated: true)
        textField.inputAccessoryView = toolBar
        
        let dateFormatter = DateFormatter()
        dateFormatter.dateStyle = .medium
        dateFormatter.timeStyle = .medium
        textField.text = dateFormatter.string(from: self.setDatePicker.date)
        
        self.view.endEditing(true)  
   }

@objc func onClickDoneButton() {
    self.view.endEditing(true)
}

 @objc private func dateChangeEvent(_ dataPicker: UIDatePicker){
    toDoAlert.textFields?.first?.text = dataPicker.date.description
}

你可以这样添加

let datePicker = UIDatePicker()
let toDoAlert = UIAlertController(title: "Add ToDo", message: "Add a new task", preferredStyle: .alert)
toDoAlert.addTextField { textField in
    textField.inputView = self.datePicker
}

或者

let datePicker = UIDatePicker()
let toDoAlert = UIAlertController(title: "Add ToDo", message: "Add a new task", preferredStyle: .alert)
toDoAlert.addTextField()
toDoAlert.textFields?.first?.inputView = datePicker

以及设置选择器值。

let datePicker = UIDatePicker()
let toDoAlert = UIAlertController(title: "Add ToDo", message: "Add a new task", preferredStyle: .alert)

@IBAction func showAlert(_ sender: UIButton) {
    datePicker.addTarget(self, action: #selector(dateChangeEvent), for: .valueChanged)
    toDoAlert.addTextField { textField in
        textField.inputView = self.datePicker
    }
//=== Other Code ====
}

@objc private func dateChangeEvent(_ datePicker: UIDatePicker) {
    toDoAlert.textFields?.first?.text = datePicker.date.description
}