ios 如何启用滑动以删除 TableView 中的单元格?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8983094/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-30 16:27:18  来源:igfitidea点击:

How to enable swipe to delete cell in a TableView?

iosuitableviewuiswipegesturerecognizer

提问by Amogh Talpallikar

I have a UIViewControllerthat implements TableViews delegate and datasourceprotocols. Now I want to add "swipe to delete" gesture to cells.

我有一个UIViewController实现 TableViews 委托和数据源协议的。现在我想向单元格添加“滑动删除”手势。

How should I go about it.

我该怎么办。

I have given a blank implementation of commitEditingStylemethod and also set the Editing property to YES.

我给出了commitEditingStyle方法的空白实现,并将 Editing 属性设置为 YES。

Still the swipe feature is not coming .

仍然没有刷卡功能。

Now Do I need to separately add UISwipeGestureto each cell ?

现在我需要单独添加UISwipeGesture到每个单元格吗?

Or am I missing something ?

或者我错过了什么?

采纳答案by Kyr Dunenkoff

You don't have to set editing:YESif you need to show Delete button on cell swipe. You have to implement tableView:canEditRowAtIndexPath:and return YES from there for rows you need to edit/delete. This is not necessary when your tableView's dataSource is a subclass of UITableViewContoller - this method, if not overridden, returns YES by default. In all other cases you have to implement it.

您不必设置editing:YES是否需要在单元格滑动时显示删除按钮。tableView:canEditRowAtIndexPath:对于需要编辑/删除的行,您必须实现并从那里返回 YES。当您的 tableView 的 dataSource 是 UITableViewContoller 的子类时,这不是必需的 - 此方法如果未被覆盖,默认情况下返回 YES。在所有其他情况下,您必须实施它。

EDIT:Together we have found the problem - tableView:editingStyleForRowAtIndexPath:returned UITableViewCellEditingStyleNoneif table wasn't in editing mode.

编辑:我们一起发现了问题-tableView:editingStyleForRowAtIndexPath:返回UITableViewCellEditingStyleNone如果表中编辑模式没有。

回答by Dj S

As Danhas commented above, you need to implement the following table view delegate methods:

正如Dan在上面评论的那样,您需要实现以下表视图委托方法:

  1. tableView:canEditRowAtIndexPath:
  2. tableView:commitEditingStyle:forRowAtIndexPath:
  1. tableView:canEditRowAtIndexPath:
  2. tableView:commitEditingStyle:forRowAtIndexPath:

Note: I have tried this in iOS 6 and iOS 7.

注意:我已经在 iOS 6 和 iOS 7 中尝试过这个。

- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Return YES - we will be able to delete all rows
    return YES;
}

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Perform the real delete action here. Note: you may need to check editing style
    //   if you do not perform delete only.
    NSLog(@"Deleted row.");
}

回答by Can Aksoy

// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Return NO if you do not want the specified item to be editable.
    return YES;
}



// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    }   
    else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}

回答by Masa S-AiYa

Please try this code in swift,

请快速尝试此代码,

override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
   // let the controller to know that able to edit tableView's row 
   return true
}

override func tableView(tableView: UITableView, commitEditingStyle editingStyle UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath)  {
   // if you want to apply with iOS 8 or earlier version you must add this function too. (just left in blank code)
}

override func tableView(tableView: UITableView, editActionsForRowAtIndexPath indexPath: NSIndexPath) -> [UITableViewRowAction]?  {
   // add the action button you want to show when swiping on tableView's cell , in this case add the delete button.
   let deleteAction = UITableViewRowAction(style: .Default, title: "Delete", handler: { (action , indexPath) -> Void in

   // Your delete code here.....
   .........
   .........
   })

   // You can set its properties like normal button
   deleteAction.backgroundColor = UIColor.redColor()

   return [deleteAction]
}

回答by David M. Syzdek

Try adding the following to your class:

尝试将以下内容添加到您的课程中:

// Override to support conditional editing of the table view.
- (BOOL) tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    return(YES);
}

回答by Thiru

Conclusion of Kyr Dunenkoffchat is

Kyr Dunenkoff聊天的结论是

- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath {

}

should not be defined if you need delete button to appear on swipe.

如果您需要在滑动时出现删除按钮,则不应定义。

回答by GabeV

If you are using an NSFetchedResultsControllerDelegateto populate the table view, this worked for me:

如果您使用 anNSFetchedResultsControllerDelegate来填充表格视图,这对我有用:

  • Make sure tableView:canEditRowAtIndexPathreturns true always
  • In your tableView:commitEditingStyle:forRowAtIndexPathimplementation, do not delete the row directly from the table view. Instead, delete it using your managed object context, e.g.:

    if editingStyle == UITableViewCellEditingStyle.Delete {
        let word = self.fetchedResultsController.objectAtIndexPath(indexPath) as! Word
        self.managedObjectContext.deleteObject(word)
        self.saveManagedObjectContext()
    }
    
    func saveManagedObjectContext() {
        do {
            try self.managedObjectContext.save()
        } catch {
            let saveError = error as NSError
            print("\(saveError), \(saveError.userInfo)")
        }
    }
    
  • 确保tableView:canEditRowAtIndexPath始终返回 true
  • 在您的tableView:commitEditingStyle:forRowAtIndexPath实现中,不要直接从表视图中删除该行。相反,使用您的托管对象上下文删除它,例如:

    if editingStyle == UITableViewCellEditingStyle.Delete {
        let word = self.fetchedResultsController.objectAtIndexPath(indexPath) as! Word
        self.managedObjectContext.deleteObject(word)
        self.saveManagedObjectContext()
    }
    
    func saveManagedObjectContext() {
        do {
            try self.managedObjectContext.save()
        } catch {
            let saveError = error as NSError
            print("\(saveError), \(saveError.userInfo)")
        }
    }
    

回答by kgaidis

In my experience, seems like you must have editingon UITableViewset to NOfor swiping to work.

根据我的经验,好像你必须editingUITableView设置为NO用于刷卡的工作。

self.tableView.editing = NO;

self.tableView.editing = NO;

回答by user501836

After iOS 8.0, you can custom you action in

在 iOS 8.0 之后,你可以自定义你的动作

- (nullable NSArray<UITableViewRowAction *> *)tableView:(UITableView *)tableView editActionsForRowAtIndexPath:(NSIndexPath *)indexPath

回答by JZAU

This is the swift version

这是快速版本

// Override to support conditional editing of the table view.
override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
    // Return NO if you do not want the specified item to be editable.
    return true
}

// Override to support editing the table view.
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
    if editingStyle == .Delete {
        // Delete the row from the data source
        tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
    } else if editingStyle == .Insert {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }    
}