【问题标题】:How to remove a cell from tableView with animation through IBAction? iOS Swift 3.0如何通过 IBAction 从 tableView 中删除带有动画的单元格? iOS 斯威夫特 3.0
【发布时间】:2018-01-28 02:34:36
【问题描述】:

我正在构建一个待办事项列表应用程序,并且在我的视图控制器中保存了一个任务模型数组和 tableView。

这个 tableView 中的每个单元格都包含几个 UI 元素,其中一个是 UIView,它实际上是一个复选框,由 Skyscanner 的 pod 实现: https://github.com/Marxon13/M13Checkbox

我想在用户点击复选框时删除一个单元格(带有动画)。

我为 UIView 设置了 IBAction,我知道要删除数组中的哪个元素(我标记了每个 UIView)但我不能使用该方法

tableView.deleteRows(at: [IndexPath], with: UITableViewRowAnimation)

因为我没有索引路径。 我想找到一种很好的方法来删除带有索引的单元格,最好不保存 indexPath 变量(我尝试过,但不确定如何正确实现它,因为可以从各种索引中删除单元格)。

感谢您的帮助!

【问题讨论】:

  • 如果您知道行和节,则创建索引路径并删除该行。确保在调用 tableView.deleteRows 之前删除数组的项目
  • IndexPath 是行和部分,如果你只有一个部分并且你已经标记了你的行,你可以轻松地重新创建 IndexPath
  • 刚刚发布了答案,感谢两位的帮助!

标签: ios iphone swift uitableview uiview


【解决方案1】:

cellForRowatIndexPath 中设置复选框/按钮上的操作事件,如下所示。不要忘记在每个复选框/按钮上添加标签。

cell.btnCounter.tag = indexPath.row
cell.btnCounter.addTarget(self, action: #selector(self.buttonClicked), for: .touchUpInside)

您需要按如下方式处理事件

func buttonClicked(_ sender: UIButton) {
        //Here sender.tag will give you the tapped checkbox/Button index from the cell
        your_array.remove(at: sender.tag) //Remove your element from array
        tableView.deleteRows(at: [IndexPath(row: sender.tag, section: 0))], with: .automatic) //Hope it is in section 0
    }

希望对你有帮助

【讨论】:

    【解决方案2】:

    // 检查此快照代码

    @IBAction func  btnAction(_ sender : UIButton){
    
            // get Indexpath with Button position
    
             let buttonPosition = sender.convert(CGPoint.zero, to: self.tableview)
             let indexPath: IndexPath? = tableview.indexPathForRow(at: buttonPosition)
    
            self.yourArrayDatasource.remove(at: indexPath.row)  // don't forget to replace your array of data source
    
            self.tableview.deleteRows(at: [indexPath!], with: UITableViewRowAnimation.automatic)
    
    
        }
    

    希望对你有帮助

    【讨论】:

      【解决方案3】:

      感谢所有提供帮助的人! 我正在回答我自己的问题,因为它是您的答案的组合!

      正如 Puneet Sharma、Reinier Melian 和 Yun CHEN 所说,我设法在函数内部创建了一个索引路径。 Puneet 的评论非常重要,您必须从数组中删除元素删除单元格之前。

      PS。 也许我可以在我问这个问题之前创建 IndexPath 方式,但是在

      行中
      self.tableView.deleteRows(at: [IndexPath(row: checkbox.tag, section: 0)], with: .automatic)
      

      Xcode 根本不会自动完成这个初始化。

      这是删除单元格的代码,就像我想要的那样:

             @IBAction func completeBtnPressed(_ sender: Any) {
          let checkbox = (sender as! M13Checkbox)
          self.tasks.remove(at: checkbox.tag)
      
          self.tableView.deleteRows(at: [IndexPath(row: checkbox.tag, section: 0)], with: .automatic)
      }
      

      非常感谢!

      【讨论】:

        猜你喜欢
        • 2023-03-31
        • 2017-07-22
        • 2023-03-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-08-02
        相关资源
        最近更新 更多