Is it possible to detect a Shift + Enter key combination on iOS in a UITextView
?
2 Answers
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!")
}
3 Comments
Yoshiharu Yamada
Your answer helps me a lot! Thank you! I have implemented the custom textview in gist: gist.github.com/yosshi4486/ff37ffee79886fd2beabde375f65ba9a.
paulvs
Did this work with the iOS keyboard? In my tests, it only works with a bluetooth-connected physical keyboard.
paulvs
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).
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)
}
}
... shouldChangeTextInRange...
delegate method and see if there is any difference between Enter and Shift+Enter.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.