5

Is it possible to detect a Shift + Enter key combination on iOS in a UITextView?

5
  • What do you want to do differently? Use ... shouldChangeTextInRange... delegate method and see if there is any difference between Enter and Shift+Enter. Commented Jan 14, 2015 at 0:27
  • But how would do detect if the shift key is pressed or active when return is pressed? Commented Jan 14, 2015 at 0:29
  • As I said, implement that UITextViewDelegate delegate method and look at the value to see if there is any difference. Probably not. And again, what is your goal? There may be another way. Commented Jan 14, 2015 at 0:31
  • There isn't. :) I want to do separate actions if it's a return or shift + return. Commented Jan 14, 2015 at 0:32
  • I assumed you wanted to do something different. What is it? No one can offer help if you keep it a secret. :) Commented Jan 14, 2015 at 0:34

2 Answers 2

7

Using Swift you can intercept the combination Shift + Enter in a UIResponder subclass using something like this:

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

func handleShiftEnter(command: UIKeyCommand) {
    print("Combo pressed! Default action intercepted!")
}
Sign up to request clarification or add additional context in comments.

3 Comments

Your answer helps me a lot! Thank you! I have implemented the custom textview in gist: gist.github.com/yosshi4486/ff37ffee79886fd2beabde375f65ba9a.
Did this work with the iOS keyboard? In my tests, it only works with a bluetooth-connected physical keyboard.
FWIW, I'm trying to allow for soft newlines by tapping return while holding down the Shift key on the iOS virtual keyboard (similar to this).
0

Here is a subclass of UITextView that detects enter key and shift enter key combination on an external physical keyboard.

protocol TextViewWithKeyDetectionDelegate: AnyObject {
    func enterKeyWasPressed(textView: UITextView)
    func shiftEnterKeyPressed(textView: UITextView)
}

class TextViewWithKeyDetection: UITextView {
    weak var keyDelegate: TextViewWithKeyDetectionDelegate?
    
    override var keyCommands: [UIKeyCommand]? {
        [UIKeyCommand(input: "\r", modifierFlags: .shift, action: #selector(shiftEnterKeyPressed)),
         UIKeyCommand(input: "\r", modifierFlags: [], action: #selector(enterKeyPressed))]
    }
    
    @objc func shiftEnterKeyPressed(sender: UIKeyCommand) {
        keyDelegate?.shiftEnterKeyPressed(textView: self)
    }
    
    @objc func enterKeyPressed(sender: UIKeyCommand) {
        keyDelegate?.enterKeyWasPressed(textView: self)
    }
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.