在swift中删除表视图中的一行

Sun*_*mar 11 uitableview ios swift

我试图在表视图中删除一行.我已经实现了所需的方法但是当我水平滑动行时没有删除按钮.我已经搜索过,我到处都找到了相同的解决方案,但在我的情况下它不起作用.我不知道我在哪里弄错了.有人可以帮我吗?

func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool 
{
    return true
}

func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) 
{
     if editingStyle == .Delete 
     {
        dataHandler.deletePeripheral(indexPath.row)
        tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
     }
}
Run Code Online (Sandbox Code Playgroud)

use*_*143 40

如果以下编码对您有帮助,我会很高兴

func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool 
{
    return true
}

func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) 
{
     if editingStyle == .Delete 
     {
        yourArray.removeAtIndex(indexPath.row) 
        self.tableView.reloadData()   
     }
}
Run Code Online (Sandbox Code Playgroud)

SWIFT 3.0

func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool
{
    return true
}

func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath)
{
   if editingStyle == .delete
   {
      yourArray.remove(at: indexPath.row)
      tblDltRow.reloadData()
   }
}
Run Code Online (Sandbox Code Playgroud)

你必须刷新表.

  • tableView.deleteRowsAtIndexPaths([indexPath],withRowAnimation:.Fade)比重新加载整个表更好 (12认同)

Ant*_*ton 7

func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {

        if (editingStyle == UITableViewCellEditingStyle.Delete) {


            self.tableView.beginUpdates()
            self.arrayData.removeObjectAtIndex(indexPath.row) // also remove an array object if exists.
            self.tableView.deleteRowsAtIndexPaths(NSArray(object: NSIndexPath(forRow: indexPath.row, inSection: 2)), withRowAnimation: UITableViewRowAnimation.Left)
            self.tableView.endUpdates()

        }
Run Code Online (Sandbox Code Playgroud)

  • beginUpdate()和endUpdate()解决了我的问题,当我试图在Swift 3中调用DeleteRow时应用程序崩溃 (2认同)