ios - 从 UICollectionView 的一个部分中删除一行似乎不会删除关联的标题

标签 ios swift header uicollectionview uicollectionviewlayout

我有自己的自定义 UICollectionViewLayout,它为给定部分中的每一行添加一个自定义标题,当我从该部分删除一个项目时,我遇到以下崩溃:

*** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'no UICollectionViewLayoutAttributes instance for -layoutAttributesForSupplementaryElementOfKind: UICollectionElementKindSectionHeader at path {length = 2, path = 2 - 0}'

这对我来说毫无意义。我刚刚删除了 2 - 0 处的行,为什么它试图从我的布局类中请求标题?

这是我删除行的代码:

collectionView?.performBatchUpdates({
            self.trackControllers.remove(at: index)
            if self.collectionView?.numberOfItems(inSection: 2) > index {
                self.collectionView?.deleteItems(at: [IndexPath(row: index, section: 2)])
            }
        })

删除后该部分是否为空,或者是否还有其他行,这无关紧要,它似乎仍然在请求我刚刚删除的行的标题。

最佳答案

所以我设法自己解决了这个问题。

显然,UICollectionView 将继续请求相同的补充 View ,直到删除动画结束。为了解决这个问题,我必须覆盖 indexPathsToDeleteForSupplementaryView(ofKind elementKind: String) -> [IndexPath]。现在,这很愚蠢地没有向我们提供有关哪些 indexPaths 已被删除的任何信息,因此您必须自己在 prepare(forCollectionViewUpdates updateItems: [UICollectionViewUpdateItem])

中跟踪这一点

这是解决我的问题的代码:

fileprivate var deletedIndexPaths = [IndexPath]()
override func prepare(forCollectionViewUpdates updateItems: [UICollectionViewUpdateItem]) {
    deletedIndexPaths.removeAll()
    super.prepare(forCollectionViewUpdates: updateItems)

    let newlyDeletedItemsInSection2 = updateItems.filter({ $0.updateAction == .delete }).filter({ $0.indexPathBeforeUpdate?.section == 2 })
    let newlyDeletedIndexPaths = newlyDeletedItemsInSection2.flatMap({ $0.indexPathBeforeUpdate })
    deletedIndexPaths.append(contentsOf: newlyDeletedIndexPaths)
}

override func indexPathsToDeleteForSupplementaryView(ofKind elementKind: String) -> [IndexPath] {
    return deletedIndexPaths
}

override func finalizeCollectionViewUpdates() {
    deletedIndexPaths.removeAll()
}

(请注意,我拥有的唯一具有标题的部分是第 2 部分)

关于ios - 从 UICollectionView 的一个部分中删除一行似乎不会删除关联的标题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40998111/

相关文章:

ios - 如何使 preferredStatusBarStyle 成为一个函数

swift - 在 swift 函数中返回 nil

c++ - CMake 和绝对标题路径

header - 去掉报告的顶部标题

ios - 如何将 Linphone 集成到 IOS Swift - 开发 iOS 7/8

javascript - 如何让 React Native 的 ScrollView 初始缩放不为 1?

swift - UISearchController searchBar 不更新 barTintColor

php - 从 cURL 获取内容类型

objective-c - Xcode 4.3 停止构建 XIB 文件

ios - 我想获取当前时间,但是我收到了格林尼治标准时间。怎么了?