UITextField在UIDatePicker操作事件时不触发操作事件
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了UITextField在UIDatePicker操作事件时不触发操作事件相关的知识,希望对你有一定的参考价值。
我有一个更新我的textField的datePicker。一旦textField数据更改应该执行操作(例如验证数据)。问题是在datePicker更新textField之后,textField不执行任何操作,无论我在textField上使用什么动作事件,例如.ValueChanged.I无法弄清楚问题是什么。我注意到,如果我要在textField中键入内容,则action事件会起作用。这是我的代码:
class CustomTextField: UITextField, UITextFieldDelegate {
var customDelegate : CustomTextFieldDelegate?
enum type {
case standard
case date
}
var textFieldType : type = .standard {
didSet{
switch self.textFieldType {
case .standard:
break
case .date:
let datePicker = UIDatePicker.MMMddyyyy
self.inputView = datePicker
datePicker.addTarget(self, action: #selector(refreshOnDatePicker(_:)), for: .valueChanged)
self.addTarget(self, action: #selector(checkFieldInput), for: .applicationReserved)
break
}
}
}
@objc private func checkFieldInput(sender: CustomTextField){
guard let fieldInput = self.text else { return }
switch sender.textFieldType {
case .standard:
break
case .date:
customDelegate?.isTextFieldVerified = !fieldInput.isEmpty
break
}
}
@objc private func refreshOnDatePicker(_ selector: UIDatePicker){
self.text = selector.date.formattedMMMMddyyyy
}
}
fileprivate extension UIDatePicker {
class var MMMddyyyy : UIDatePicker {
let currentDate: NSDate = NSDate()
let calendar: NSCalendar = NSCalendar(calendarIdentifier: NSCalendar.Identifier.gregorian)!
calendar.timeZone = NSTimeZone(name: "UTC")! as TimeZone
let components: NSDateComponents = NSDateComponents()
components.calendar = calendar as Calendar
components.year = -100
let minDate: NSDate = calendar.date(byAdding: components as DateComponents, to: currentDate as Date, options: NSCalendar.Options(rawValue: 0))! as NSDate
let dp = UIDatePicker()
dp.datePickerMode = .date
dp.minimumDate = minDate as Date
dp.maximumDate = currentDate as Date
dp.backgroundColor = UIColor.white
return dp
}
}
fileprivate extension Date {
/// date formatted type "MMMM dd, yyyy"
var formattedMMMMddyyyy: String {
let formatter = DateFormatter()
formatter.dateFormat = "MMMM dd, yyyy"
return formatter.string(from: self)
}
}
答案
试试这个
@objc private func refreshOnDatePicker(_ selector: UIDatePicker){
self.text = selector.date.formattedMMMMddyyyy
self.checkFieldInput(sender:self)
}
以上是关于UITextField在UIDatePicker操作事件时不触发操作事件的主要内容,如果未能解决你的问题,请参考以下文章
如何使用相同的 UIDatePicker 分别在 2 UITextField 中获取日期和时间
从 UITextField 单击事件 MonoTouch 在 UIDatePicker 中选择日期
切换视图控制器时如何保留 UIDatePicker 和 UITextField 值?
是否可以在 Swift 中拥有来自同一个 UITextField 的 UIPickerView 和 UIDatePicker?