UIDatePicker:选择当前日期(快速)

时间:2019-05-02 05:43:50

标签: swift uidatepicker

我有一个UIDatePicker,其中某些日期是通过首字母设置的。借助addTarget,我听了valueChanged事件,当车轮旋转时,一切正常。

我希望允许用户直接选择初始日期(例如,通过单击它)。但是现在只有车轮旋转时才发生此事件。要输入当前日期,用户将必须:

  1. 输入新日期
  2. 转到上一个日期

我的代码:

class Picker {
    init() {
        let datePicker = UIDatePicker()
        datePicker.setDate(Date(), animated: false) // Set initial date
        datePicker.addTarget(self, action: #selector(handleDatePicker(sender:)), for: .valueChanged)
    }

    @objc func handleDatePicker(sender: UIDatePicker) {
        print(sender.date)
    }
}

Picker()

截屏:

enter image description here

解决方案:

最正确的解决方法是使用UIToolBar按钮添加Done。可以在这里找到代码:example with UIToolBar

1 个答案:

答案 0 :(得分:-1)

在datePicker中的“单击完成”按钮上选择第一个索引值

func pickUp(_ textField:UITextField){

    // UIPickerView
    self.myPickerView = UIPickerView(frame:CGRect(x: 0, y: 0, width: self.view.frame.size.width, height: 216))
    self.myPickerView.delegate = self
    self.myPickerView.dataSource = self
    self.myPickerView.backgroundColor = UIColor.white
    textField.inputView = self.myPickerView

    // ToolBar
    let toolBar = UIToolbar()
    toolBar.barStyle = .default
    toolBar.isTranslucent = true
    toolBar.tintColor = UIColor.darkGray
    toolBar.sizeToFit()

    // Adding Button ToolBar
    let doneButton = UIBarButtonItem(title: "Done", style: .plain, target: self, action: #selector(UrVC.doneClick))
    let spaceButton = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil)
    let cancelButton = UIBarButtonItem(title: "Cancel", style: .plain, target: self, action: #selector(UrVC.cancelClick))
    toolBar.setItems([cancelButton, spaceButton, doneButton], animated: false)
    toolBar.isUserInteractionEnabled = true
    textField.inputAccessoryView = toolBar

}

@objc func doneClick(){

    pickerTxtfld.resignFirstResponder()
    let indexPath = myPickerView.selectedRow(inComponent: 0)
    pickerTxtfld.text = dataArray[indexPath]


}
@objc func cancelClick() {
    pickerTxtfld.resignFirstResponder()
}