【问题标题】:How to detect a swipe-to-delete gesture in a customized UITableviewCell?如何检测自定义 UITableviewCell 中的滑动删除手势?
【发布时间】:2011-09-04 07:06:03
【问题描述】:

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

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

也许我必须使用 UIGestureRecognizer?

【问题讨论】:

    标签: iphone ios ipad uitableview gestures


    【解决方案1】:

    这里有两种方法可以用来避免删除按钮:

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

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

    【讨论】:

    • 谢谢!完美工作! :)
    • 如果用户不删除行,还有 - (void)tableView:(UITableView*)tableView didEndEditingRowAtIndexPath:(NSIndexPath *)indexPath
    【解决方案2】:

    如果你想做一些完全不同的事情,给每个 tableview 单元格添加一个 UISwipeGestureRecognizer。

    // 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];
            //..
        }
    }
    

    【讨论】:

    • vmanjz 的答案要好得多,因为您不必为每个表格单元格创建 UISwipeGestureRecognizer。与一张非常大的桌子一样,您可能会看到一些严重的延迟,从而产生了如此多的手势识别器。
    • 您可以将手势识别器添加到表格视图中。查看我对类似问题的回答:stackoverflow.com/a/4604667/550177
    • 这种方法的一个问题是它只能识别 .Ended 状态,而不是 .Began 状态
    猜你喜欢
    • 1970-01-01
    • 2012-01-24
    • 1970-01-01
    • 1970-01-01
    • 2012-08-28
    • 2011-05-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多