gpt4 book ai didi

ios - resignFirstResponder() 不适用于日期选择器

转载 作者:行者123 更新时间:2023-12-01 19:32:33 29 4
gpt4 key购买 nike

我有一个很简单的CustomIDatePicker写在 中的类 swift 5 ,顶部有一个工具栏,其中包含一个“完成”按钮。问题是,按下此按钮时键盘从未缩回。我尝试了4种不同的方法,请参阅下面的详细信息:

import UIKit

class CustomDatePicker: UIDatePicker {

var zTextField: UITextField!

let toolbar = UIToolbar()

convenience init(textField: UITextField) {
self.init()

// bar buttons
let doneBtn = UIBarButtonItem(barButtonSystemItem: .done, target: self, action: #selector(donePressed(sender:)))

toolbar.sizeToFit()
toolbar.setItems([doneBtn], animated: true)

self.datePickerMode = .date

// link up the Text Field
zTextField = textField
zTextField.inputAccessoryView = toolbar
zTextField.inputView = self
}

@objc func donePressed (sender: UIBarButtonItem) {
print("done pressed") // this line appeared in the debugger

//self.resignFirstResponder()
//self.inputView?.resignFirstResponder()
//self.endEditing(true)
self.inputView?.endEditing(true) // tried all of these 4, but keyboard always remained in view
}
}

一个非常简单的 ViewController 来测试这个类:
class ViewController: UIViewController {

@IBOutlet weak var theTextField: UITextField!

override func viewDidLoad() {
super.viewDidLoad()

let datePicker = CustomDatePicker(textField: theTextField)
}
}

任何帮助将不胜感激!

最佳答案

实现 UITextField 委托(delegate)功能

func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool {
return false
}
@objc func donePressed (sender: UIBarButtonItem) {
print("done pressed")

self.zTextField.resignFirstResponder() // new line
}

关于ios - resignFirstResponder() 不适用于日期选择器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61654716/

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