swift UIText字段:按下clearButton后放弃键盘

mdfafbf1  于 2022-12-10  发布在  Swift
关注(0)|答案(1)|浏览(108)

我在故事板中有一个UITextfield
ClearButton设置为“始终可见”

searchTextField.addTarget(self, action: #selector(searchTextFieldDidChange(textField:)), for: .editingChanged)

当文本字段更改时,调用此方法

@objc func searchTextFieldDidChange(textField: UITextField){
    if textField.text == "" {
        textField.resignFirstResponder()
    }
    fireSearch()
}

当我使用退格键清除文本字段时,调用了textField.resignFirstResponder(),键盘按我的要求消失了。
当我使用清除按钮清除文本字段时,调用textField.resignFirstResponder(),键盘消失并立即再次出现。
当我点击清除按钮时,键盘一直关闭,我该怎么办?

dtcbnfnu

dtcbnfnu1#

给予这个...

// conform to UITextFieldDelegate
class ViewController: UIViewController, UITextFieldDelegate {
    
    // assuming this is created in Storyboard
    @IBOutlet var searchTextField: UITextField!

    override func viewDidLoad() {
        super.viewDidLoad()

        searchTextField.addTarget(self, action: #selector(searchTextFieldDidChange(textField:)), for: .editingChanged)

        // set the delegate
        searchTextField.delegate = self
    }
    
    @objc func searchTextFieldDidChange(textField: UITextField){
        if textField.text == "" {
            textField.resignFirstResponder()
        }
        fireSearch()
    }
    func textFieldShouldClear(_ textField: UITextField) -> Bool {
        // clear the text
        //  Note: this does NOT fire searchTextFieldDidChange()
        textField.text = ""

        // resign
        textField.resignFirstResponder()

        // if you want to fire the search after text has been cleared
        //fireSearch()

        // return false to stop the default action of the clear button
        return false
    }
    func fireSearch() {
        print(#function)
    }

}

相关问题