2016-10-26 17 views
1

我想在用戶按下硬件鍵盤上的向下箭頭時在表視圖中選擇一行。目前,我只是試圖打印日誌,而我似乎無法使其工作。根據其他類似問題的答案,這裏是我到目前爲止:如何使用UIKeyCommand

- (NSArray *)keyCommands { 
UIKeyCommand *downArrowKeyCommand = [UIKeyCommand keyCommandWithInput:UIKeyInputDownArrow 
                 modifierFlags:0 
                   action:@selector(hardwareKeyboardDownArrowPressed)]; 

return @[downArrowKeyCommand]; 
} 

- (BOOL)canBecomeFirstResponder { 
return YES; 
} 

- (void)hardwareKeyboardDownArrowPressed { 

NSLog(@"Down arrow pressed on external keyboard"); 

} 

所有幫助表示讚賞!

回答

1

我不知道你特別的錯誤;可能是因爲您沒有在您的方法中添加(id)sender。我想到如何做到這一點。我會在下面添加我的代碼:

- (BOOL)canBecomeFirstResponder { 
    return YES; 
} 

- (NSArray *)keyCommands { 
    return @[[UIKeyCommand keyCommandWithInput:UIKeyInputDownArrow modifierFlags:0 action:@selector(moveDownOneRow:) discoverabilityTitle:@"Select row down"], 
      [UIKeyCommand keyCommandWithInput:UIKeyInputUpArrow modifierFlags:0 action:@selector(moveUpOneRow:) discoverabilityTitle:@"Select row up"]]; 
} 

- (void)moveDownOneRow:(id)sender { 
    NSIndexPath *indexPath = [self.tableView indexPathForSelectedRow]; 

    if (indexPath == nil) { 
     indexPath = [NSIndexPath indexPathForRow:0 inSection:0]; 
    } else { 
     if ((indexPath.row + 1) < [self.tableView numberOfRowsInSection:0]) { 
      indexPath = [NSIndexPath indexPathForRow:indexPath.row+1 inSection:0]; 
     } 
    } 

    [self.tableView selectRowAtIndexPath:indexPath animated:YES scrollPosition:UITableViewScrollPositionMiddle]; 
} 

- (void)moveUpOneRow:(id)sender { 
    NSIndexPath *indexPath = [self.tableViewindexPathForSelectedRow]; 

    if (indexPath == nil) { 
     indexPath = [NSIndexPath indexPathForRow:([self.tableView numberOfRowsInSection:0]-1) inSection:0]; 
    } else { 
     if ((indexPath.row - 1) >= 0) { 
      indexPath = [NSIndexPath indexPathForRow:indexPath.row-1 inSection:0]; 
     } 
    } 

    [self.tableView selectRowAtIndexPath:indexPath animated:YES scrollPosition:UITableViewScrollPositionMiddle]; 
}