首页 文章

如何在自定义的UITableviewCell中检测滑动到删除手势?

提问于
浏览
13

我已经定制了一个UITableViewCell,我想实现“轻扫删除” . 但我不想要默认的删除按钮 . 相反,我想做一些不同的事情 . 实现这个最简单的方法是什么?当用户滑动删除单元格时,是否有一些方法被调用?我可以阻止默认删除按钮出现吗?

现在我想我必须实现我自己的逻辑,以避免默认删除按钮,并缩小在UITableViewCell的默认实现中滑动删除中发生的动画 .

也许我必须使用UIGestureRecognizer?

2 回答

  • 14

    如果要执行完全不同的操作,请将UISwipeGestureRecognizer添加到每个tableview单元格 .

    // Customize the appearance of table view cells.
    - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
    {
        static NSString *CellIdentifier = @"Cell";
    
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
        if (cell == nil) {
            cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
        }
    
        // Configure the cell.
    
    
        UISwipeGestureRecognizer* sgr = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(cellSwiped:)];
        [sgr setDirection:UISwipeGestureRecognizerDirectionRight];
        [cell addGestureRecognizer:sgr];
        [sgr release];
    
        cell.textLabel.text = [NSString stringWithFormat:@"Cell %d", indexPath.row];
        // ...
        return cell;
    }
    
    - (void)cellSwiped:(UIGestureRecognizer *)gestureRecognizer {
        if (gestureRecognizer.state == UIGestureRecognizerStateEnded) {
            UITableViewCell *cell = (UITableViewCell *)gestureRecognizer.view;
            NSIndexPath* indexPath = [self.tableView indexPathForCell:cell];
            //..
        }
    }
    
  • 16

    以下是两种可用于避免删除按钮的方法:

    - (void)tableView:(UITableView *)tableView willBeginEditingRowAtIndexPath:(NSIndexPath *)indexPath
    

    - (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
    

相关问题