簡體   English   中英

如何檢測自定義 UITableviewCell 中的滑動刪除手勢?

[英]How to detect a swipe-to-delete gesture in a customized UITableviewCell?

我已經定制了一個 UITableViewCell,我想實現“滑動刪除”。 但我不想要默認的刪除按鈕。 相反,我想做一些不同的事情。 實現這一點的最簡單方法是什么? 當用戶滑動刪除單元格時,是否有一些方法會被調用? 我可以阻止出現默認的刪除按鈕嗎?

現在我想我必須實現我自己的邏輯,以避免在 UITableViewCell 的默認實現中滑動刪除時發生的默認刪除按鈕和縮小動畫。

也許我必須使用 UIGestureRecognizer?

如果您想做一些完全不同的事情,請將 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];
        //..
    }
}

這里有兩種方法可以用來避免刪除按鈕:

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

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM