Swift: 单击按钮时断言失败

Swift: Assertion failure when button clicked

Swift 3

我有一个包含多行的 table 视图,每行都有一个按钮(使用 indexPath.row),当单击该按钮时,它会从第 1 部分移动该行( testArray) 到第 0 节 (followedArray)。但是当使用搜索栏搜索 testArray 并单击一行的按钮时,它会崩溃。

现在,当使用搜索栏时,testArray 被过滤到一个名为 filteredArray 的新数组中。该按钮应该将行从 filteredArray 移动到 followedArray.

在没有搜索的情况下,按钮可以正常工作,只有在使用搜索栏时才会崩溃。

我做错了什么?

这是 错误 我得到:

CustomCellSwift[1473:391841] *** Assertion failure in -[UITableView _endCellAnimationsWithContext:], /BuildRoot/Library/Caches/com.apple.xbs/Sources/UIKit/UIKit-3600.5.2/UITableView.m:1315

新建议:是否与filteredArray替换table视图时testArray和followedArray的indexPath.row冲突有什么关系?

Deleting from UISearchController's filtered search results

我使用的代码:

@IBAction func followButtonClick(_ sender: UIButton!) {

    // Adding row to tag
    let buttonPosition = (sender as AnyObject).convert(CGPoint.zero, to: self.myTableView)
    if let indexPath = self.myTableView.indexPathForRow(at: buttonPosition) {

        // Change Follow to Following
        (sender as UIButton).setImage(UIImage(named: "follow.png")!, for: .normal)
        cell.followButton.isHidden = true
        cell.followedButton.isHidden = false

        // Checking wether to import from testArray or filteredArray to followedArray
        if !(searchController.isActive && searchController.searchBar.text != "") {

            self.myTableView.beginUpdates()

            // ----- Inserting Cell to followedArray -----
            followedArray.insert(testArray[indexPath.row], at: 0)
            myTableView.insertRows(at: [IndexPath(row: 0, section: 0)], with: .fade)

            // ----- Removing Cell from testArray -----
            testArray.remove(at: indexPath.row)
            let rowToRemove = indexPath.row
            self.myTableView.deleteRows(at: [IndexPath(row: rowToRemove, section: 1)], with: .fade)

            self.myTableView.endUpdates()

        }
        else {

            self.myTableView.beginUpdates()

            // ----- Inserting Cell to followedArray -----
            followedArray.insert(filteredArray[indexPath.row], at: 0)
            myTableView.insertRows(at: [IndexPath(row: 0, section: 0)], with: .fade)

            // ----- Removing Cell from filteredArray -----
            filteredArray.remove(at: indexPath.row)
            let rowToRemove = indexPath.row
            self.myTableView.deleteRows(at: [IndexPath(row: rowToRemove, section: 0)], with: .fade)

            self.myTableView.endUpdates()

        }
    }
}

所以我找到了答案,我使用 insert at sections 方法将对象添加到数组中,而不是仅使用 insert,因为我只有 1 个部分。

let testObject: Test = filteredArray[indexPath.row]
let indexOfObjectInArray = testArray.index(of: testObject)
followedArray.insert(testObject, at: 0)