簡體   English   中英

如何在 Swift 中添加滑動以從 UITableViewController 中刪除表格單元格?

[英]How to add swipe to remove table cells from UITableViewController in Swift?

Swift 5.1 的教程並不多,我還是個新手。 我想知道如何使 tableView 刪除覆蓋函數適用於我的代碼。 它給了我一個關於對象的錯誤,因為它們是一個未解析的標識符。 另外插入中的 go 會是什么?

 override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return posts.count

}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "Cell")
    let mainImageView = cell?.viewWithTag(2) as! UIImageView
    mainImageView.image = posts[indexPath.row].mainImage
    let mainLabel = cell?.viewWithTag(1) as! UILabel
    mainLabel.text = posts[indexPath.row].name
    return cell!
}

override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
    if editingStyle == .delete {
        objects.remove(at: indexPath.row) // Here I get an error because objects is an unresolved identifier. 
        tableView.deleteRows(at: [indexPath], with: .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. I am also confused as to what goes here. 
    }
}

您需要的所有信息都可以在這里找到。

此方法允許委托自定義位於 indexPath 的單元格的編輯樣式。 如果委托未實現此方法並且 UITableViewCell object 是可編輯的(即,它的 isEditing 屬性設置為 true),則單元格將為其設置 UITableViewCell.EditingStyle.delete 樣式。

這就是你所缺少的:

https://developer.apple.com/documentation/uikit/uitableviewdelegate/1614869-tableview

override func tableView(_ tableView: UITableView, 
   editingStyleForRowAt indexPath: IndexPath) -> UITableViewCell.EditingStyle {
return .delete
}

在這里,您使用 object 刪除索引路徑的數據,這是錯誤的,您使用“posts”命名數組在表視圖上顯示值。 因此,這個“posts”數組包含在表格視圖中可見的對象。 因此,在這里,當您想要刪除 object 時,這意味着您必須從“posts”數組中刪除對象。 在隨附的 function 下方進行了一些更改,您可以檢查它是否適合您。

override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == .delete {
    posts.remove(at: indexPath.row) // Here I get an error because objects is an unresolved identifier. 
    tableView.deleteRows(at: [indexPath], with: .fade)
} else if editingStyle == .insert {  
    posts.append("Here insert what you want") //inside append you can append/insert values to the array
    tableView.reloadData()
}
}

暫無
暫無

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

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