Search code examples
objective-cuitableviewtvos

tvOS UITableView scroll to cell


I'm starting a new project for tvOS. I have created a programmatically UITableView inside my viewcontroller. Inside the UITableView i have created 5 cells. Until now everything works, but the problem happens when i'm trying to programmatically scroll to cell 4 so i'm doing:

 NSIndexPath *indexPath = [NSIndexPath indexPathForRow:3
                                            inSection:0];

[tableView scrollToRowAtIndexPath:indexPath
                     atScrollPosition:UITableViewScrollPositionTop
                             animated:YES];

But the code above does nothing. It always start at first cell and highlight it as the selected one. I want to be able to programmatically start at another cell and it most be highlight so when i use the arrow keys down or up it scroll from there and not first cell. Please help me in doing that


Solution

  • You should do next: In viewController that respond for UITableView, implement next function:

    - (UIView *)preferredFocusedView {
        return self.tableView;
    }
    

    where tableView is your table, and after that, override next function

    - (NSIndexPath *)indexPathForPreferredFocusedViewInTableView:(UITableView *)tableView  {
        return [NSIndexPath indexPathForRow:_exerciseIndex inSection:0];
    }
    

    where _exerciseIndex index that you need to focus.