簡體   English   中英

如何通過IBAction從動態中刪除tableView中的單元格? iOS Swift 3.0

[英]How to remove a cell from tableView with animation through IBAction? iOS Swift 3.0

我正在構建一個todo-list應用程序,我在視圖控制器中持有一個任務模型數組和tableView。

此tableView中的每個單元格都包含多個UI元素,其中一個是UIView,實際上是一個復選框,由Skyscanner的pod實現: https//github.com/Marxon13/M13Checkbox

當用戶點擊復選框(帶動畫)時,我想刪除一個單元格。

我為UIView設置了一個IBAction,我知道要刪除的數組中的哪個元素(我標記了每個UIView)但我不能使用該方法

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

因為我沒有索引路徑。 我想找到一個很好的方法來刪除索引的單元格,最好不要保存indexPath變量(我試過但不知道如何正確實現它,因為可以從各種索引中刪除單元格)。

謝謝你的幫助!

感謝所有幫助過的人! 我正在回答我自己的問題,因為這是你的答案的組合!

正如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)
}

非常感謝!

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
    }

希望這對你有所幫助

//檢查此快照代碼

@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)


    }

我希望它對你有所幫助

暫無
暫無

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

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