1

I have custom keyboard which I added as textfield.inputView. But my shouldChangeCharactersIn at UITextFieldDelegate doesn’t work? Any idea?

Rob
  • 415,655
  • 72
  • 787
  • 1,044
Kate
  • 21
  • 1

1 Answers1

0

You have to implement the call to the delegate method yourself prior to inserting the text into the control.

For example, let’s assume you have some function for handling tap of a button, which calls UIKeyInput method insertText. Just check that the delegate implements the method and that it did not return false:

@objc func didTapButton(_ sender: ...) {
    guard let range = target?.selectedRange else { return } // assumes `target` was defined to conform to `UITextInput`, using extension shared below

    let string = ...

    if let textField = target as? UITextField, textField.delegate?.textField?(textField, shouldChangeCharactersIn: range, replacementString: string) == false {
        return
    }

    if let textView = target as? UITextView, textView.delegate?.textView?(textView, shouldChangeTextIn: range, replacementText: string) == false {
        return
    }

    target?.insertText(string)                              // assumes `target` was defined to conform to `UIKeyInput`
}

Where:

extension UITextInput {
    var selectedRange: NSRange? {
        guard let textRange = selectedTextRange else { return nil }

        let location = offset(from: beginningOfDocument, to: textRange.start)
        let length = offset(from: textRange.start, to: textRange.end)
        return NSRange(location: location, length: length)
    }
}

Clearly, the details are dependent upon your custom keyboard implementation (the above is based upon https://stackoverflow.com/a/57275689/1271826), but hopefully it illustrates the basic idea.

Rob
  • 415,655
  • 72
  • 787
  • 1,044