有没有办法检测何时从连接到 iOS 设备的外部键盘按下“返回”键,而不是点击屏幕键盘的“返回”键?
这可以通过公共 API 实现吗?
我的班级担任
UITextFieldDelegate
,我接到的电话来自:
- (BOOL)textFieldShouldReturn:(UITextField *)textField
但是当调用它时,
textField.text
返回文本字段中存在的字符,但不返回发出的回车符。
对于物理或虚拟键盘,按下“Return”键不会调用-textField:shouldChangeCharactersInRange:replacementString
。
UIKeyCommand
来区分硬件键盘的 Return
extension ViewController {
override var keyCommands: [UIKeyCommand]? {
return [
UIKeyCommand(input: "\r",
modifierFlags: [],
action: #selector(keyCommand_return)),
]
}
@objc private func keyCommand_return() {
/// handle return
}
}
UITextField
的子类应该可以工作:
protocol TextFieldKeyDetectionDelegate: AnyObject {
func enterKeyWasPressed(textField: UITextField)
func shiftEnterKeyPressed(textField: UITextField)
}
class TextFieldWithKeyDetection: UITextField {
weak var keyDelegate: TextFieldKeyDetectionDelegate?
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(textField: self)
}
@objc func enterKeyPressed(sender: UIKeyCommand) {
keyDelegate?.enterKeyWasPressed(textField: self)
}
}