如果我同时拥有开始日期和结束日期文本字段,我是否必须创建2个不同的DatePickers?

时间:2017-05-13 03:39:45

标签: ios swift datepicker

当我点击开始日期文本字段和结束日期文本字段时,我有UIDatePicker工作,但它更新的所有内容都是开始日期。

我是否需要创建单独的日期选择器,或者是否可以为您触摸的字段工作?

func createDatePicker() {

    // format for picker
    datePicker.datePickerMode = .date

    // toolbar
    let toolbar = UIToolbar()
    toolbar.sizeToFit()

    // bar button item
    let doneButton = UIBarButtonItem(barButtonSystemItem: .done, target: nil, action: #selector(donePressed))
    toolbar.setItems([doneButton], animated: false)

    startDate.inputAccessoryView = toolbar
    endDate.inputAccessoryView = toolbar

    // assigning date picker to text field
    startDate.inputView = datePicker
    endDate.inputView = datePicker

} 

1 个答案:

答案 0 :(得分:0)

实际上有一种方法可以使用 1 UITextField实例来控制UIDatePicker多个实例。一种方法是通过它UITextField继承的UIView属性来跟踪当前选定的.tag

为清楚起见,请使用enum来区分文本字段:

fileprivate enum TextField: Int {
    case startDateField
    case endDateField
}

定义属性并使用UIDateFormatter在日期和字符串之间来回翻译:

// MARK: - Properties

@IBOutlet weak var startDateTextField: UITextField!
@IBOutlet weak var endDateTextField: UITextField!
fileprivate var datePicker: UIDatePicker!
fileprivate var currentTextFieldResponder = TextField.startDateField
fileprivate let dateFormatter: DateFormatter = {
    let formatter = DateFormatter()
    formatter.dateStyle = .full
    return formatter
}()

配置动作方法并将其连接到日期选择器,在每次更改值后触发: 注意:文本字段的.tag属性也可以在SB

中设置
// MARK: - View Lifecycle    

override func viewDidLoad() {
    super.viewDidLoad()
    // DatePicker base configuration
    datePicker = UIDatePicker()
    datePicker.datePickerMode = .date
    datePicker.addTarget(self, action: #selector(datePickerValueChanged(sender:)), for: .valueChanged)
    // Textfields configuration
    startDateTextField.inputView = datePicker
    startDateTextField.tag = 0
    startDateTextField.delegate = self
    endDateTextField.inputView = datePicker
    endDateTextField.tag = 1
    endDateTextField.delegate = self
}

根据当前选定的UITextField属性,更新相应的文本字段:

// MARK: - Actions    

func datePickerValueChanged(sender: UIDatePicker) {
    let selectedDateText = dateFormatter.string(from: sender.date)
    switch currentTextFieldResponder {
    case .startDateField:
        startDateTextField.text = selectedDateText
    case .endDateField:
        endDateTextField.text = selectedDateText
    }
}

更新currentTextFieldResponder属性并将datePicker用户界面重置为之前的选择:

// MARK: - UITextFieldDelegate

extension ViewController: UITextFieldDelegate {

    // Just after a text object becomes first responder
    func textFieldDidBeginEditing(_ textField: UITextField) {
        // Update current text responder and reset datePicker's date
        currentTextFieldResponder = TextField(rawValue: textField.tag)!
        if
            let dateText = textField.text,
            let date = dateFormatter.date(from: dateText) {
            datePicker.date = date
        }
    }
}

作为奖励,设置UIDatePicker.date属性会自动为选取器列设置动画。