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
}

你可能感兴趣的:(textFieldShouldClear 方法内执行 resignFirstResponder 无效的问题)