Search code examples
objective-cuikeycommand

How to use UIKeyCommand


I'm trying to select a row in a table view when a user presses the down arrow on a hardware keyboard. For now, I'm just trying to print a log, and I can't seem to get it to work. As per the other similar questions' answers, here's what I have so far:

- (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");

}

All help is appreciated!


Solution

  • I don't know your particular mistake; it might be that you haven't added a (id)sender to your method. I figured how to do this. I'll add my code below:

    - (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];
    }