Home > Blockchain >  Detect shift return key when UITextView is the responder
Detect shift return key when UITextView is the responder

Time:08-10

I want to detect if the user presses either just "return" key or "shift return" key on the external keyboard to perform two different actions when the UITextView is the responder.

It works when UITextView is not responding by using UIKeyCommands

override var keyCommands: [UIKeyCommand]? {
        return [
            UIKeyCommand(input: "\r", modifierFlags: [], action: #selector(taskOne)),
            UIKeyCommand(input: "\r", modifierFlags: .shift, action: #selector(taskTwo)),
        ]
}

But when UITextView is being edited, it just adds a new line and doesn't detect these UIKeyCommands.

How can I solve this issue?

CodePudding user response:

override press began function

override func pressesBegan(_ presses: Set<UIPress>, with event:  UIPressesEvent?) {
    guard let key = presses.first?.key else { return }
    
    switch key.keyCode {
    case .keyboardReturn:
        if key.modifierFlags == .shift {
            taskTwo()
        } else {
            // not the state for plus you want, pass it
            taskOne()
        }
        super.pressesBegan(presses, with: event)
        break
    default:
        super.pressesBegan(presses, with: event)
    }
}

and override func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool

for UITextViewDelegate

check this answer

  • Related