3

我有以下代码来计算表(tableview1)中选定行的数量。

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell * cell = [tableView cellForRowAtIndexPath:indexPath];
    if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"Cell"];
    }
    int count = 0;
    selectedindex1 = indexPath.row;
    for (NSIndexPath *indexPath in tableview1.indexPathsForSelectedRows) {
        count = count + 1;
    }
    rowcount = count;
}

其中 selectedindex1 和 rowcount 是整数变量。

只要您假设用户不会选择已选择的行,此代码就可以工作。如果这样做,应用程序将无法判断正确的选定行数,因为这样的操作不会触发 didSelectRowAtIndexPath 方法。有没有更好的方法来计算所选行的数量?

谢谢您的帮助。

4

3 回答 3

6

我认为这很简单:

[[tableView indexPathsForSelectedRows] count]

再说一次,这正是您的代码所做的:

int count = 0;
for (NSIndexPath *indexPath in tableview1.indexPathsForSelectedRows) {
    count = count + 1;
}
rowcount = count;

你到底想要发生什么?

于 2013-03-11T23:26:27.737 回答
2

也许只保留一个已选择的 indexPath 的运行数组。这样,您就不必担心选择相同的两次。

- 在 vi​​ewDidLoad 中初始化一个数组

  NSMutableArray *yourSelectedRowsArray = [[NSMutableArray alloc]init]; 

- 然后在 didSelectRowAtIndexPath... 做这样的事情:

if(![yourSelectedRowsArray containsObject:indexPath])
{
    [yourSelectedRowsArray addObject:indexPath];
}

NSLog(@"the number of selected rows is %d",yourSelectedRowsArray.count);

- 在 didDeselectRowAtIndexPath.. 中做类似的事情:

if([yourSelectedRowsArray containsObject:indexPath])
    {
        [yourSelectedRowsArray removeObject:indexPath];
    }

NSLog(@"the number of selected rows now is %d",yourSelectedRowsArray.count);

然后只需在您想使用它的任何地方访问数组的计数,您就会拥有选定的行数。

于 2013-03-11T23:22:19.337 回答
2

好的。就像下面这样简单。

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    rowcount =  [[tableView indexPathsForSelectedRows] count];
}

- (void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(NSIndexPath *)indexPath {
    rowcount =  [[tableView indexPathsForSelectedRows] count];
}
于 2013-03-11T23:43:44.300 回答