Bluetooth Keyboard Replace

来源:互联网 发布:淘宝双十一利弊 编辑:程序博客网 时间:2024/06/07 08:39

蓝牙键盘的按键事件替换

寻找了许久,真的是心塞死了,一直都没有关于如何让蓝牙键盘和文本编辑框脱轨的方法。然后就T-T。。。。。

后来发现了常用来处理 keyCommands 这个属性,这个本身是用来处理热键的。
keyCommands 会转接转接侦听的按键事件,为什么我们要这样做,目的是什么??

为什么要转接蓝牙键盘的按键事件??

由于输入的时候,系统不会区分蓝牙键盘和软键盘的输入,都会统一通过以下的两个 UITextViewDelegate 协议的接口,那对于蓝牙键盘可能存在的组合键就存在着问题。比如Alt + Enter,Shift + Enter,Enter。这三个快捷键最终的结果都是返回“\n”。那就无法区分对待了。根本不知道是来自软键盘的return键,还是软键盘的组合键。

- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text;- (void)textViewDidChange:(UITextView *)textView;

这样做的意义是什么??

当使用 keyCommands 时,被转调的蓝牙键盘按键将会调到指定函数区域,而不会走原来 UITextViewDelegate 这样就非常赞了,可以让我们的快捷键做到我们设定的效果,而不会混搅。

怎样使用 keyCommands ???

重写UITextView的属性keyCommands,只要把自己需要侦听的热键,都侦听就好了。如果没有侦听的还是走UITextViewDelegate

/** * * */- (NSArray*)keyCommands{    UIKeyCommand *aEnterCommand    = [UIKeyCommand keyCommandWithInput: @"\r" modifierFlags: UIKeyModifierCommand action: @selector(enterCombination:)];    UIKeyCommand *aEnterShift      = [UIKeyCommand keyCommandWithInput: @"\r" modifierFlags: UIKeyModifierShift action: @selector(enterCombination:)];    UIKeyCommand *aEnterControl    = [UIKeyCommand keyCommandWithInput: @"\r" modifierFlags: UIKeyModifierControl action: @selector(enterCombination:)];    UIKeyCommand *aAlterEnter      = [UIKeyCommand keyCommandWithInput: @"\r" modifierFlags: UIKeyModifierAlternate action: @selector(enterCombination:)];    return @[aAlterEnter, aEnterCommand, aEnterShift, aEnterControl];}/** *   * */- ( void ) enterCombination:(UIKeyCommand*)keyCommand{}

注意可能导致keyCommands无效的基类

如果重写了下面的基类方法,但是没有让转调的方法return YES,将会导致转调方法不执行。
我的猜想,由于 UIKeyCommand 创建时,并没有指明是谁去接事件,那就是 UITextView 本身自己去接转调事件。那如果它本身去接收,那他可能需要询问是否此方法可以调用。

- (BOOL)canPerformAction:(SEL)action withSender:(id)sender
0 0
原创粉丝点击