首页 > 解决方案 > Auto hidden keyboard after enter six characters

问题描述

I am a swift beginner. I implemented this functionality in ViewController, but I don't want to write such code in every ViewController. I want to implement it through a protocol, but something is wrong.

import UIKit

@objc protocol TextFieldAutoHiddenKeyboard: class {
    var textFieldAutoHidenLenth: UInt {get set} 
}

extension TextFieldAutoHiddenKeyboard where Self: UIViewController {

    func autoHiddenKeyboardWhenFillUpTextFiled(textField textF: UITextField, autoHidenLenth: UInt) {
        textFieldAutoHidenLenth = autoHidenLenth

        let textFieldDidChangeActionName = "textFieldDidChange(textField:)"
        let textFieldDidChangeAction = Selector(textFieldDidChangeActionName)
        textF.addTarget(self, action: textFieldDidChangeAction, for: .editingChanged)

        let dismissKeyboardActionName = "dismissKeyboard"
        let dismissKeyboardAction = Selector(dismissKeyboardActionName)
        let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: dismissKeyboardAction)
        view.addGestureRecognizer(tap)
      //textF.addTarget(self, action: #selector(textFieldDidChange(textField:autoHidenLenth:)), for: .editingChanged)
    }

    func textFieldDidChange(textField: UITextField) {
        if let text = textField.text {
            if text.count == textFieldAutoHidenLenth {
                textField.resignFirstResponder()
            }
        }
    }

    func dismissKeyboard() {
        view.endEditing(true)
    }

    //@objc func textFieldDidChange(textField: UITextField, autoHidenLenth: UInt) {
    //    if let text = textField.text {
    //        if text.count == autoHidenLenth {
    //           textField.resignFirstResponder()
    //        }
    //    }
    //}
}
  1. Why my app crash. EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0)
  2. By creating an Action using a Selector, #selector(textFieldDidChange(textField:autoHidenLenth:)), I don't know how to pass the second argument to function. For example, the parameter autoHidenLenth.
  3. How to implement this function correctly through Protocol?

Demo picture
(source: recordit.co)

标签: iosswiftkeyboarduitextfielddelegate

解决方案


您不应该使用字符串文字构造选择器,而是使用#selector(textFieldDidChange(textField:)),然后您会看到选择器方法需要暴露给Objective C。
因此您应该能够通过编写来修复它:

@objc func textFieldDidChange(textField: UITextField) {
    if let text = textField.text {
        if text.count == textFieldAutoHidenLenth {
            textField.resignFirstResponder()
        }
    }
}

推荐阅读