如何获取用户didSelectRowAtIndexPath的次数?

时间:2013-10-13 17:54:35

标签: ios uitableview

在我的UITableView上,我想检查用户点击同一行的次数。

如果用户点击了同一行三次,我想从UITableView中删除该行。

有人可以请我解决这个问题吗?我试过了:

for (NSIndexPath *indexPath in self.tableView.indexPathsForSelectedRows) {
    count = count + 1;
    NSLog(@"rowCount %d indexPath.row %@", count, indexPath);
}

但这不会增加用户点击行的计数次数。

4 个答案:

答案 0 :(得分:1)

创建一个NSMutableDictionary属性,其中键是indexPath,值是当前的点击数。 e.g。

@property (nonatomic,strong) NSMutableDictionary *rowTaps;

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {

if (!self.rowTaps) {
  self.rowTaps = [NSMutableDictionary dictionary];
}

[self.rowTaps setObject:[NSNumber numberWithInt:[(NSNumber *)[self.rowTaps objectForKey:indexPath]intValue]] forKey:indexPath];

if ([(NSNumber *)[self.rowTaps objectForKey:indexPath]intValue] == 3) {
     // Perform Delete Action - Delete row, and update datasource
}
}

每次在单元格上进行选择时,都会对字典执行检查,然后执行必要的操作。

答案 1 :(得分:1)

假设您只想在用户连续三次选择同一个单元格时删除该行。

创建另一个变量lastSelectedRow,保留最后选定的行。 (在实施线下面创建)

@implementation myViewController
{
   NSInteger = lastSelectedRow;
}

接下来,您应该验证该行是否等于最后一行,递增并检查是否必须删除该行:

for (NSIndexPath *indexPath in self.tableView.indexPathsForSelectedRows) {

    // If the last selected row is the same, increment the counter, else reset the counter to 1
    if (indexPath.row == lastSelectedRow) count++;
    else
    {
      lastSelectedRow = indexPath.row;
      count = 1;
    }

    // Now we verify if the user selected the row 3 times and delete the row if so
    if (count >= 3) [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];

    NSLog(@"rowCount %d indexPath.row %@", count, indexPath);
}

希望它有所帮助。

答案 2 :(得分:0)

在界面中创建以下属性:

@interface ViewController () <UITableViewDelegate,UITableViewDataSource>

@property (assign,nonatomic) int counter;

@end

在您的实现中,您可以按如下方式递增计数器:

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    self.counter++;
    NSLog(@"the count is %i",self.counter);
}

答案 3 :(得分:0)

创建一个NSMutableDictionary并将密钥设置为单元格索引,然后为值设置count(首先为1)。当计数达到3时,你可以做你需要的。

 //fake cell index (from indexpath)
    NSNumber * pretendCellIndex = [NSNumber numberWithInt:4];

    //Dict to track ocurrences
    NSMutableDictionary *index = [[NSMutableDictionary alloc]init];

    //If the dict has the index, increment
    if ([index objectForKey:pretendCellIndex]) {

        //Get value for the index
        int addOne = [[index objectForKey:pretendCellIndex] intValue];
        addOne++;

        //Add back to index
        [index setObject:[NSNumber numberWithInt:addOne] forKey:pretendCellIndex];

        //Your condition
        if (addOne>=3) {
            //do what you need
        }
    }else{
    //Havent seen so add
        [index setObject:[NSNumber numberWithInt:1] forKey:pretendCellIndex];
    }
相关问题