首页 > 解决方案 > 有大量单元格时删除和插入行崩溃

问题描述

我在表格视图单元格插入和删除方面遇到问题。根据用户选择的模式,我基本上有 1 个 tableView 可以在其中显示 3 个不同的数组。

当用户单击不同的模式时,我想为初始单元格删除设置动画,然后为其他单元格的插入设置动画。

当我的数组非常小(大小为 5 左右)但当它变得大于我崩溃时,这是有效的。我们是否限制删除未在 tableViews 中显示的 indexPaths?

无论如何,我的代码如下:

 func viewDidLoad() {
    let o1 = "1"
    let o2 = "2"
    let o3 = "3"
    array1 = [o1, o2, o2, o1, o3, o1, o2] 
    array2 = [o3, o2, o2, o1, o3, o1, o2, o2, o2, o1, o3, o1, o2]
    array3 = [o3, o1, o2, o2, o2, o1, o3, o1, o2]
}

func animateTableTransitions() {
    let array: [String]!
    let previousArray: [String]!
    let index = ModeEnum.index
    let previousIndex = ModeEnum.index //Custom enum that mains the index at which each mode is presented
    var indexPaths = [IndexPath]()
    var previousIndexPaths = [IndexPath]()
    switch (currentMode, previousMode) {
    case (.mode1, .mode2):
        array = array1
        previousArray = array2
    case (.mode1, .mode3):
        array = array1
        previousArray = array3
    case (.mode2, .mode1):
        array = array2
        previousArray = array1
    case (.mode2, .mode3):
        array = array2
        previousArray = array3
    case (.mode3, .mode1):
        array = array3
        previousArray = array1
    case (.mode3, .mode2):
        array = array3
        previousArray = array2
    default:
        return
    }

    for index in 0..<array.count {
        indexPaths.append(IndexPath(row: index, section: 0))
    }

    for index in 0..<previousArray.count {
        previousIndexPaths.append(IndexPath(row: index, section: 0))
    }

    if previousTranslationMode == .text && textModeOn {
        previousIndexPaths.append(IndexPath(item: textArray.count, section: 0))
    }

    let firstAnimationType: UITableViewRowAnimation = index < previousIndex ? .right : .left
    let secondAnimationType: UITableViewRowAnimation = index < previousIndex ? .left : .right

    tableView.performBatchUpdates({
        self.tableView.deleteRows(at: previousIndexPaths, with: firstAnimationType)
        self.tableView.insertRows(at: indexPaths, with: secondAnimationType)
    }, completion: nil)

如前所述,当数组没有填充那么多项目时,不会发生任何问题。但是当数组填充似乎超过 5 个项目时,我遇到了问题。任何帮助将不胜感激。

谢谢你的时间,艾伦

标签: iosswiftuitableviewtableviewperformbatchupdates

解决方案


推荐阅读