如何以编程方式转到UITableView中的下一个/上一个单元格?

Vla*_*lov 4 iphone objective-c uitableview

我有UItableview和两个按钮Next和Previous点击,我应该选择上一个/下一个单元格?可能吗?此外,如何记住用户最后点击的单元格,以便在启动时选择它?

mji*_*awi 9

实现UITableViewDelegate并在didSelectRowAtIndexPath中保存当前选定的索引:

NSIndexPath *currentSelection;

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    currentSelection = indexPath;
}
Run Code Online (Sandbox Code Playgroud)

然后在您的按钮操作中,您可以执行类似...

- (IBAction)didTapNextButton:(id)sender{

    //Remember to check boundaries before just setting an indexpath or your app will crash!
    if(currentSelection){
        currentSelection = [NSIndexPath indexPathForRow:currentSelection.row+1 inSection:currentSelection.section];
    }else{
        currentSelection = [NSIndexPath indexPathForRow:0 inSection:0];
    }

    [self.tableView selectRowAtIndexPath:currentSelection animated:YES scrollPosition: UITableViewScrollPositionTop];

}
Run Code Online (Sandbox Code Playgroud)