获取UITableView的选中索引

106

我想为UITableView获取选中的索引。

我已经编写了以下代码:

NSIndexPath *index = [NSIndexPath indexPathForRow:1 inSection:0];
[tableView scrollToRowAtIndexPath:index 
                 atScrollPosition:UITableViewScrollPositionTop 
                         animated:YES];

这对于第一个项目总是有效的。我想在indexPathForRow中有所选索引。

请帮忙。 谢谢。

5个回答

219
NSIndexPath *selectedIndexPath = [tableView indexPathForSelectedRow];

5
如果您允许多项选择,请考虑使用:-(NSArray *)indexPathsForSelectedRows。 - yura
一旦您拥有了 *selectedIndexPath,对于我来说访问 long pathRow = [selectedIndexPath row()];long pathSection = [selectedIndexPath section()]; 是非常有用的,当您需要特定的选择时(请注意,NSIntegertypedef long,这来自 C 背景,因为两者都需要 %ld,所以更有意义)。 - Jonathan Weinraub

8

获取当前选定的行。 如果您只有一个部分,这可能会有所帮助。

- (NSUInteger)currentSellectedRowIndex
{
    NSIndexPath *selectedIndexPath = [self.tableView indexPathForSelectedRow];
    if (selectedIndexPath) {
        return selectedIndexPath.row;
    }
    else {
        return NSNotFound;
    }
}

5
请使用以下代码
CGPoint location =[sender locationInView:self.tableView];
NSIndexPath *swipedIndexPath = [self.tableView indexPathForRowAtPoint:location];
UITableViewCell *swipedCell  = [self.tableView cellForRowAtIndexPath:swipedIndexPath];
NSIndexPath *indexPath = [self.tableView indexPathForCell:swipedCell];

4

Swift 4.2

let selectedIndexPath = tableView.indexPathForSelectedRow

这是一个可选的返回值。


1
直接而简单。谢谢! - AntonSack

4
在didSelectRowAtIndexPath方法中,将一个声明为NSIndexPath的接口设置为返回的indexpath。然后你就可以滚动到那个变量了。如果需要帮助,请留言,我可以提供一些示例代码。

或者,您可以使用Chris的方法以更快的速度使用。上述方法提供了更多的控制,并且可以由您的(例如)详细视图控制器进行修改。 - Kolin Krewinkel

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接