簡體   English   中英

UISegmentController與UITableviewController

[英]UISegmentController with UITableviewController

我有一個具有段控制器的表視圖,它分別具有兩個段類別1和2。 當我將商品添加到類別1時,它做的很好,但是當我將商品添加到類別2時,應用程序崩潰,說“由於未捕獲的異常“ NSInternalInconsistencyException”而終止應用程序,原因:“試圖將第0行插入第0節,但更新后的第0部分中只有0行。 這是我插入表視圖的代碼。

對於類別1:

func itemDetailViewController(controller: ItemDetailViewController, didFinishAddingItem item: NoToDoItem) {
    let newRowIndex = items.count

    items.append(item)

    let indexPath = NSIndexPath(forRow: newRowIndex, inSection: 0)
    let indexPaths = [indexPath]
    tableView.insertRowsAtIndexPaths(indexPaths, withRowAnimation: .Automatic)

    dismissViewControllerAnimated(true, completion: nil)
}

對於類別2:

func itemDetailViewController(controller: ItemDetailViewController, didFinishAddingNotSureItem notSureItem: NotSureItem) {
    let newRowIndex = notSureItems.count

    notSureItems.append(notSureItem)

    let indexPath = NSIndexPath(forRow: newRowIndex, inSection: 0)
    let indexPaths = [indexPath]
    tableView.insertRowsAtIndexPaths(indexPaths, withRowAnimation: .Automatic)

    dismissViewControllerAnimated(true, completion: nil)
}

您確定表格顯示的是當前添加到的類別嗎? 嘗試這個:

func itemDetailViewController(controller: ItemDetailViewController, didFinishAddingItem item: NoToDoItem) {
    let newRowIndex = items.count

    items.append(item)
    if segmentBar.selectedSegmentIndex == 0 {
        let indexPath = NSIndexPath(forRow: newRowIndex, inSection: 0)
        let indexPaths = [indexPath]
        tableView.insertRowsAtIndexPaths(indexPaths, withRowAnimation: .Automatic)
    }
    dismissViewControllerAnimated(true, completion: nil)
}

並對didFinishAddingNotSureItem進行相同操作。

還要確保在更改類別時重新加載表視圖。

UITableView必須始終與數據源保持同步。 如果數據源可以在后台線程中更改,則必須格外小心。

將某些內容添加到數據源后,請盡快調用beginUpdate / insert / endUpdate。 所以試試這個:

tableView.beginUpdates()

let indexPath = NSIndexPath(forRow: newRowIndex, inSection: 0)
let indexPaths = [indexPath]
tableView.insertRowsAtIndexPaths(indexPaths, withRowAnimation: .Automatic)

tableView.endUpdates()

PS:信任數據源模型對象notSureItems的設置正確,並且numberOfRowsInSection函數返回正確的計數。

編輯:發表OP評論

您正在嘗試以錯誤的索引添加行。 表格視圖索引以0開頭,因此這是推導新單元格索引的方式:

notSureItems.append(notSureItem)
let newRowIndex = notSureItems.count - 1

另外,在itemDetailViewControllernumberOfRowsInSection函數中放置一個斷點以檢查模型值。

暫無
暫無

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

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