检测iOS键盘上的Shift + Enter

fcg9iug3  于 2022-11-19  发布在  iOS
关注(0)|答案(2)|浏览(173)

UITextView中是否可以检测到iOS上的Shift + Enter组合键?

klr1opcd

klr1opcd1#

使用Swift,您可以在UIResponder子类中截取Shift + Enter组合,如下所示:

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!")
}
dwbf0jvd

dwbf0jvd2#

下面是UITextView的一个子类,它检测外部物理键盘上的Enter键和Shift Enter键组合。

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)
    }
}

相关问题