gpt4 book ai didi

ios - 如何快速在 IQKeyboardManagerSwift 上添加日期选择器 View

转载 作者:行者123 更新时间:2023-11-28 23:23:46 24 4
gpt4 key购买 nike

我是 Swift 的新手,在 IQKeyboardManagerSwift 上显示日期选择器 View 时遇到问题

我正在尝试这样的代码,但它不起作用

func textFieldDidBeginEditing(_ textField: UITextField) {
self.dischargeDateTextField = textField

// Create a date picker for the date field.
let picker = UIDatePicker()
picker.datePickerMode = .date
picker.addTarget(self, action: #selector(updateDateField(sender:)), for: .valueChanged)

// If the date field has focus, display a date picker instead of keyboard.
// Set the text to the date currently displayed by the picker.
textField.inputView = picker
textField.text = formatDateForDisplay(date: picker.date)
}

// Called when the date picker changes.

@objc func updateDateField(sender: UIDatePicker) {
dischargeDateTextField?.text = formatDateForDisplay(date: sender.date)
}


// Formats the date chosen with the date picker.

fileprivate func formatDateForDisplay(date: Date) -> String {
let formatter = DateFormatter()
formatter.dateFormat = "dd MMM yyyy"
return formatter.string(from: date)
}

我需要“yyyy-mm-dd”中的日期格式,但它只显示为图片

enter image description here

我这样修改代码

 fileprivate func formatDateForDisplaySurgery(date: Date) -> String {
let formatter = DateFormatter()
formatter.dateFormat = "yyy-mm-dd"
return formatter.string(from: date)
}

但它不工作

最佳答案

viewDidLoad() 方法中添加 inputView 的代码。

override func viewDidLoad() {
super.viewDidLoad()
let picker = UIDatePicker()
picker.datePickerMode = .date
picker.addTarget(self, action: #selector(updateDateField(sender:)), for: .valueChanged)

// If the date field has focus, display a date picker instead of keyboard.
// Set the text to the date currently displayed by the picker.
self.dischargeDateTextField.inputView = picker
}

并从 textFieldDidBeginEditing 方法中删除相同的代码行。

其他的方法你都写对了。

@objc func updateDateField(sender: UIDatePicker) {
dischargeDateTextField?.text = formatDateForDisplay(date: sender.date)
}

// Formats the date chosen with the date picker.
fileprivate func formatDateForDisplay(date: Date) -> String {
let formatter = DateFormatter()
formatter.dateFormat = "dd MMM yyyy"
return formatter.string(from: date)
}

关于ios - 如何快速在 IQKeyboardManagerSwift 上添加日期选择器 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59207241/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com