如何删除表格视图单元格中的特定行?

问题描述 投票:1回答:3

我正在使用一个包含三个部分的表视图。用户可以删除第三部分的行。但是当我使用表视图委托方法删除行时,它会影响其他部分。那么我怎么能克服这个问题呢?

这是我的代码

func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
    if editingStyle == UITableViewCellEditingStyle.Delete {
      numbers.removeAtIndex(indexPath.row)    
      tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.Automatic)
    }
swift uitableview rows edit
3个回答
3
投票

如果你想限制编辑到第2节实现canEditRowAt(代码是Swift 3+)

func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
    return indexPath.section == 2
}

或者添加支票

func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
    if editingStyle == .delete && indexPath.section == 2 {
      numbers.remove(at: indexPath.row)    
      tableView.deleteRows(at: [indexPath], with: .automatic)
    }

0
投票

forRowAt indexPath: IndexPath一起使用,你有IndexPath值。

它包含.section。因此,您可以简单地检查您选择了哪个部分,然后执行删除操作。

要删除特定部分的行:

tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)

希望能帮助到你


0
投票

这样做的正确方法是

func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
    return indexPath.section == 2
}

func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath)
{
   if editingStyle == .delete && indexPath.section == 2
   {
      yourArray.remove(at: indexPath.row)
      yourtable.reloadData()
   }
}
© www.soinside.com 2019 - 2024. All rights reserved.