繁体   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