簡體   English   中英

UITableView - 破壞性UIContextualAction不會重新加載數據

[英]UITableView - Destructive UIContextualAction does not reload data

我正在嘗試使用iOS 11方式在表格視圖行中添加滑動操作。 我想添加刪除行的操作。

我的測試表視圖顯示0到9之間的數字,數據源是一個簡單的整數數組,稱為numbers

class ViewController: UIViewController {
    var numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
}

當我選擇一行時,我打印相關的numbers值:

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    print(numbers[indexPath.row])
    tableView.deselectRow(at: indexPath, animated: true)
}

我實現了新的委托trailingSwipeActionsConfigurationForRowAt ,如下所示:

func tableView(_ tableView: UITableView, trailingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? {

    let delete = UIContextualAction(style: .destructive, title: "Delete") { (_, _, completionHandler) in
        self.numbers.remove(at: indexPath.row)
        completionHandler(true)
    }

    return UISwipeActionsConfiguration(actions: [delete])
}

當我在一行上滑動時,刪除工作正常。 但是,這是我的問題,當我在刪除后選擇另一行時,關聯的IndexPath是錯誤的...

例:

  • 我選擇第一行,打印的值為0:OK。
  • 我刪除了第一行。
  • 我選擇新的第一行,打印的值是2,因為傳入的IndexPath參數是第1行,而不是第0行:不行。

我做錯了什么?

重要的是要記住,有一個模型,你的情況下的numbers數組,以及一個視圖,顯示的單元格。 numbers刪除元素時,您只更新模型。

在大多數情況下,當您編碼時,您很快就會收到錯誤,因為模型與視圖不同步。

但是,我的測試表明,當樣式為.destructive並且您將true傳遞給completionHandler Apple會為您刪除該行。 這就是你看到該行消失的原因。 但是有一些不太正確的東西,我找不到任何文件。

在此期間,只需這樣做:

self.numbers.remove(at: indexPath.row)
tableView.deleteRows(at: [indexPath], with: .automatic)
completionHandler(true)

並且始終記住,如果您使用模型進行更改,則需要更新視圖。

這是非常混亂的,調用與完成處理true更新通過刪除單元格中的觀點,但不更新表視圖的概念,其中的這剩下的細胞在其索引路徑。

圍繞這個的文檔非常少,所以我運行了一個測試,發現用true FIRST調用完成處理程序然后調用deleteRows產生“最正確”的動畫。

首先調用完成的批量更新:

tableView.beginUpdates()
completion(succeeded)
users.remove(at: indexToRemove)
tableView.deleteRows(at: [indexPath], with: .automatic)
tableView.endUpdates()

完成的批量更新稱為秒:

tableView.beginUpdates()
users.remove(at: indexToRemove)
tableView.deleteRows(at: [indexPath], with: .automatic)
completion(succeeded)
tableView.endUpdates()

完成首先調用:

completion(succeeded)
users.remove(at: indexToRemove)
tableView.deleteRows(at: [indexPath], with: .automatic)

完成稱為第二

users.remove(at: indexToRemove)
tableView.deleteRows(at: [indexPath], with: .automatic)
completion(succeeded)

圖像中期動畫:

在此輸入圖像描述

右側面板的剩余單元部分被正在移除的單元覆蓋,而左下方面板則從某處引入白色視圖。

暫無
暫無

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

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