我怎样才能响应外部键盘的箭头键?

我知道这已经被问到,我看到的唯一答案是“不需要外接键盘,因为它违背了UI准则”。 不过,我想使用这样的脚踏板: http : //www.bilila.com/page_turner_for_ipad在我的应用程序中的页面之间切换(除了滑动)。 这个翻页器模拟一个键盘,并使用向上/向下箭头键。

所以这里是我的问题:我如何回应这些箭头键事件? 它必须是可能的,因为其他的应用程序pipe理,但我画了一个空白。

对于那些在iOS 7下寻找解决scheme的人来说,有一个叫做keyCommands的新的UIResponder属性。 创buildUITextView的子类并按如下方式实现keyCommands …

@implementation ArrowKeyTextView - (id) initWithFrame: (CGRect) frame { self = [super initWithFrame:frame]; if (self) { } return self; } - (NSArray *) keyCommands { UIKeyCommand *upArrow = [UIKeyCommand keyCommandWithInput: UIKeyInputUpArrow modifierFlags: 0 action: @selector(upArrow:)]; UIKeyCommand *downArrow = [UIKeyCommand keyCommandWithInput: UIKeyInputDownArrow modifierFlags: 0 action: @selector(downArrow:)]; UIKeyCommand *leftArrow = [UIKeyCommand keyCommandWithInput: UIKeyInputLeftArrow modifierFlags: 0 action: @selector(leftArrow:)]; UIKeyCommand *rightArrow = [UIKeyCommand keyCommandWithInput: UIKeyInputRightArrow modifierFlags: 0 action: @selector(rightArrow:)]; return [[NSArray alloc] initWithObjects: upArrow, downArrow, leftArrow, rightArrow, nil]; } - (void) upArrow: (UIKeyCommand *) keyCommand { } - (void) downArrow: (UIKeyCommand *) keyCommand { } - (void) leftArrow: (UIKeyCommand *) keyCommand { } - (void) rightArrow: (UIKeyCommand *) keyCommand { } 

sorting! 我只是使用1x1px文本视图,并使用委托方法textViewDidChangeSelection textViewDidChangeSelection:

编辑:对于iOS 6我不得不将文本视图更改为50x50px(或者至less足以实际显示文本)为此工作

当踏板断开时,我也设法抑制了屏幕键盘。

这是我在viewDidLoad中的代码:

 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillAppear:) name:UIKeyboardWillShowNotification object:nil]; [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillDisappear:) name:UIKeyboardWillHideNotification object:nil]; UITextView *hiddenTextView = [[UITextView alloc] initWithFrame:CGRectMake(0, 0, 50, 50)]; [hiddenTextView setHidden:YES]; hiddenTextView.text = @"aa"; hiddenTextView.delegate = self; hiddenTextView.selectedRange = NSMakeRange(1, 0); [self.view addSubview:hiddenTextView]; [hiddenTextView becomeFirstResponder]; if (keyboardShown) [hiddenTextView resignFirstResponder]; 

在我的头文件中, keyboardShown被声明为一个bool

然后添加这些方法:

 - (void)textViewDidChangeSelection:(UITextView *)textView { /******TEXT FIELD CARET CHANGED******/ if (textView.selectedRange.location == 2) { // End of text - down arrow pressed textView.selectedRange = NSMakeRange(1, 0); } else if (textView.selectedRange.location == 0) { // Beginning of text - up arrow pressed textView.selectedRange = NSMakeRange(1, 0); } // Check if text has changed and replace with original if (![textView.text isEqualToString:@"aa"]) textView.text = @"aa"; } - (void)keyboardWillAppear:(NSNotification *)aNotification { keyboardShown = YES; } - (void)keyboardWillDisappear:(NSNotification *)aNotification { keyboardShown = NO; } 

我希望这段代码可以帮助那些正在寻找解决这个问题的人。 随意使用它。

Interesting Posts