【问题标题】:Returning value from UIDatePicker when multiple UITextFields are present存在多个 UITextField 时从 UIDatePicker 返回值
【发布时间】:2016-04-09 22:02:11
【问题描述】:

我有多个UITextField,其中一些将使用“UIDatePicker”。如何从 UIDatePicker 返回值而无需在 datePickerChanged 函数中编码 textField.text = formatter.stringFromDate(datePicker.date)

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)?
}

【问题讨论】:

    标签: ios swift uitextfield uidatepicker uitextfielddelegate


    【解决方案1】:

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

    【讨论】:

    • 感谢您的回复。嗯好吧,我应该如何初始化currentTextField?可能我不是很懂
    • @Sami, var currentTextField: UITextField? 将 currentTextField 初始化为 nil。糟糕——它不应该是@IBOutlet。
    • 您甚至可以将变量声明为隐式展开的可选项:var currentTextField: UITextField!,这样可以更轻松地处理变量。
    • 是的 - 这有效,让我保持功能通用。谢谢:)
    • @Sami,是的——大概你知道要使用 DatePicker 的 UITextField,但是如果你有很多 TextField,你最终可能不得不使用类似的结构来循环它们并挑选出你需要添加目标的那些。但这样做的好处是当用户不断选择不同的 textFileds 时——你的代码不会重复添加目标。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-11
    • 1970-01-01
    • 2016-12-25
    • 2017-02-19
    • 2016-06-29
    相关资源
    最近更新 更多