textFieldShouldClear 方法内执行 resignFirstResponder 无效的问题

textFieldShouldClear方法内调用 textField
resignFirstResponder 并未退下键盘,原因如下

    func textFieldShouldClear(_ textField: UITextField) -> Bool {
        
        print("should clear")
        
        return true
    }

    func textFieldDidBeginEditing(_ textField: UITextField) {
        print("did begin editing")
    }

    func textFieldDidEndEditing(_ textField: UITextField) {
        print("did end editing")
    }

    func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool {
        
        print("should begin editing")
        
        return true
    }
    
    func textFieldShouldEndEditing(_ textField: UITextField) -> Bool {
        
        print("should end editing")
        
        return true
    }
    
    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        
        print("should change characters")
        
        return true
    }
should begin editing
did begin editing
should change characters
should end editing
did end editing

should clear
should begin editing
did begin editing

可以看到
should begin editing
did begin editing
在 clear 之后又进行调用,这就是为什么即使调用了resignFirstResponder 也无法将键盘退下的原因。


解决方案:

func textFieldShouldClear(_ textField: UITextField) -> Bool {

    textField.resignFirstResponder()
        
    textField.text = nil
        
    return false
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容