2011-05-29 111 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