swift没有使用UIDatePicker更新textfield.text

时间:2015-03-05 00:53:57

标签: ios swift uitextfield uidatepicker

在swift中,我以编程方式声明了textField。

override func viewDidLoad() {
    super.viewDidLoad()
textField3.delegate = self

    textField3.returnKeyType = UIReturnKeyType.Next;
    datePicker.datePickerMode = UIDatePickerMode.Date
    datePicker.addTarget(self, action: Selector("handleDatePicker:"), forControlEvents: UIControlEvents.ValueChanged)
    textField3.inputView = datePicker


}

 func handleDatePicker(sender: UIDatePicker) {

    textField3.text = dateFormatter.stringFromDate(sender.date)
            }

我发现的所有其他问题与界面构建器的这个交易类似,并且没有帮助。我将如何以编程方式修复此问题?

3 个答案:

答案 0 :(得分:11)

Xcode 9•Swift 4

@objc func handleDatePicker(_ datePicker: UIDatePicker) {
    textField3.text = datePicker.date.formatted
}

override func viewDidLoad() {
    super.viewDidLoad()
    datePicker.addTarget(self, action: #selector(handleDatePicker), forControlEvents: .valueChanged)
}

extension Date {
    static let formatter: DateFormatter = {
        let formatter = DateFormatter()
        formatter.dateFormat = "EEEE, dd MMM yyyy HH:mm:ss Z"
        return formatter
    }()
    var formatted: String {
        return Date.formatter.string(from: self)
    }
}

答案 1 :(得分:3)

Swift 3 版@Leo Dabus回答:

func handleDatePicker(sender: UIDatePicker) {
        textField3.text = datePicker.date.formatted
    }

override func viewDidLoad() {
    super.viewDidLoad()
    datePicker.addTarget(self, action: #selector(handleDatePicker(sender:)), for: UIControlEvents.valueChanged)
}

extension Date {
    var formatted: String {
        let formatter = DateFormatter()
        formatter.dateFormat = "EEEE, dd MMM yyyy HH:mm:ss Z"
        return  formatter.string(from: self as Date)
    }
}

答案 2 :(得分:0)

在Swift 4中,
确认 UITableViewDelegate
使txtFChequeDate.delegate = self

func textFieldDidBeginEditing(_ textField: UITextField) {

    let datePickerView = UIDatePicker()
    datePickerView.datePickerMode = .date
    txtFChequeDate.inputView = datePickerView
    datePickerView.addTarget(self, action: #selector(handleDatePicker(sender:)), for: .valueChanged)

    if txtFChequeDate.text == "" {
        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = "dd MMM yyyy"
        txtFChequeDate.text = dateFormatter.string(from: Date())
    }
}

@objc func handleDatePicker(sender: UIDatePicker) {
    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = "dd MMM yyyy"
    txtFChequeDate.text = dateFormatter.string(from: sender.date)
}