首页 > 解决方案 > UICollectionView.setContentOffset(...) 导致 NSRangeException

问题描述

我有一个UICollectionView代表日历,加载时生成 13 个月的数据,每个月都有一个部分。UI 中有一个按钮可以在当前年份和下一年之间切换,但是当从集合的末尾滚动回当前年份的开头时,应用程序崩溃并出现以下错误。

'NSRangeException', reason: '*** -[__NSArrayM objectAtIndexedSubscript:]: index 9223372036854775806 beyond bounds [0 .. 4]'

这是导致错误的方法。

public func scrollTo(year: Int) {
    if let month = months.firstIndex(where: { $0.components.year == year }),
        let attributes = collectionView.layoutAttributesForSupplementaryElement(ofKind: UICollectionElementKindSectionHeader, at: IndexPath(item: 0, section: month)){
        let y = attributes.frame.origin.y - collectionView.contentInset.top

        // This is the line causing the error
        collectionView.setContentOffset(CGPoint(x: 0, y: y), animated: true)
    }
}

我试过打印出我的计算y值,但0每次崩溃都是如此。

可能值得注意的是,例外中提到的索引等于Int.max - 1,尽管我不知道这是如何相关的yCGFloat

标签: iosswiftuicollectionview

解决方案


我不确定动画是否导致崩溃,但在调用中更改animated为解决问题。falsesetContentOffset(...)


推荐阅读