swift没有使用UIDatePicker更新textfield.text

问题描述 投票:5回答:3

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

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

ios swift uitextfield uidatepicker
3个回答
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)
    }
}

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

0
投票

在,斯威夫特4 确认到UITableViewDelegate make 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)
}
© www.soinside.com 2019 - 2024. All rights reserved.