【问题标题】:UITextField: resign keyboard after clearButton is pressedUITextField:按下 clearButton 后退出键盘
【发布时间】:2022-12-18 03:40:31
【问题描述】:

我在故事板中有一个 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() 被调用,键盘消失并立即再次出现。

当我点击清除按钮时,键盘一直关闭,我该怎么办?

【问题讨论】:

    标签: ios swift uikit storyboard


    【解决方案1】:

    试试这个...

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

    【讨论】:

      猜你喜欢
      • 2011-12-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-11-08
      • 1970-01-01
      • 2016-07-22
      • 1970-01-01
      • 2011-03-31
      相关资源
      最近更新 更多