2011-05-29 113 views
12

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

现在我觉得我必须实现我自己的逻辑来避免默认的删除按钮和收缩,这可要刷卡在UITableViewCell中的默认实现删除动画。

也许我必须使用UIGestureRecognizer?

回答

15

如果你想完全不同的东西,添加一个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]; 
     //.. 
    } 
} 
+0

vmanjz的答案是很多,你不必创建'UISwipeGestureRecognizer更好地因'为每个表格单元格。就像一张非常大的桌子一样,您可能会看到一些严重的滞后现象,从而形成许多手势识别器 – Baza207 2014-04-07 16:45:02

+0

您可以将手势识别器添加到表格视图中。看看我的回答类似的问题:http://stackoverflow.com/a/4604667/550177 – Felix 2014-04-08 10:14:44

+0

这种方法的一个问题是,它只能识别.Ended状态,而不是.Began状态 – 2015-12-01 21:28:46

13

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

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

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

谢谢!完美工作! :) – An1Ba7 2013-09-02 11:31:26

+5

也有 - (空)的tableView:(UITableView的*)的tableView didEndEditingRowAtIndexPath:如果用户不删除行(NSIndexPath *)indexPath – Borzh 2015-06-02 15:25:29