Как я могу реагировать на клавиши со стрелками на внешней клавиатуре?
Я знаю, что об этом уже спрашивали, и единственные ответы, которые я видел, это "Не требуй внешней клавиатуры, так как это противоречит рекомендациям по пользовательскому интерфейсу". Тем не менее, я хочу использовать ножную педаль, как это: http://www.bilila.com/page_turner_for_ipad для переключения между страницами в моем приложении (в дополнение к смахиванию). Тернер страницы эмулирует клавиатуру и использует клавиши со стрелками вверх / вниз.
Итак, вот мой вопрос: как мне реагировать на эти события со стрелками? Это должно быть возможно, как и другие приложения, но я рисую пустым.
2 ответа
Для тех, кто ищет решение под iOS 7, есть новое свойство UIResponder, называемое keyCommands. Создайте подкласс UITextView и реализуйте ключевые команды следующим образом...
@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
{
}
Сортировка! Я просто использую текстовое представление 1x1px и использую метод делегата textViewDidChangeSelection:
РЕДАКТИРОВАТЬ: Для iOS 6 мне пришлось изменить представление текста на 50x50px (или, по крайней мере, достаточно для отображения текста), чтобы это работало
Мне также удалось подавить экранную клавиатуру при отключении педали.
Это мой код в 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;
}
Я надеюсь, что этот код поможет кому-то еще, кто ищет решение этой проблемы. Не стесняйтесь использовать его.