当存在多个UITextField时,从UIDatePicker返回值

时间:2016-04-09 22:02:12

标签: ios swift uitextfield uidatepicker uitextfielddelegate

我有多个UITextField,其中一些会使用' UIDatePicker'。如何在不必在textField.text = formatter.stringFromDate(datePicker.date)函数中编写datePickerChanged代码的情况下从UIDatePicker返回值?

func textFieldDidBeginEditing(textField: UITextField) {
    switch textField.tag {

        //tag = 3 is the text field that needs the date
    case 3:
        let datePicker = UIDatePicker()
        textField.inputView = datePicker
        datePicker.addTarget(self, action: "datePickerChanged:", forControlEvents: .ValueChanged)
        //textField.text = value returned from datePickerChanged
    default: break
    }
}

func datePickerChanged(datePicker: UIDatePicker) {
    let formatter = NSDateFormatter()
    formatter.dateStyle = .MediumStyle
    let dateTextValue = formatter.stringFromDate(datePicker.date)
    // how can I return (dateTextValue)?
}

1 个答案:

答案 0 :(得分:1)

您可以创建一个名为currentTextField的变量,并在您的案例陈述中将textField分配给currentTextField。然后你的datePickerChanged(_ :)函数可以使用currentTextField来设置日期。