应用程序在 `layoutAttributesForSupplementaryElement` 上崩溃

App getting crashed on `layoutAttributesForSupplementaryElement`

我正在使用 UICollectionView,在滚动到 UICollectionView 的特定部分时,我在 UICollectionView 上写了一个扩展,它在 iPhone 6 和模拟器上运行良好但在 iPhone 5 个应用程序崩溃时,我对其进行了调试,但无法找到问题所在。

这是我的代码

extension UICollectionView {

func scrollToIndexpathByShowingHeader(_ indexPath: IndexPath) {
    let sections = self.numberOfSections

    if indexPath.section <= sections {

        let attributes = layoutAttributesForSupplementaryElement(ofKind: UICollectionElementKindSectionHeader, at: indexPath)
        let topOfHeader = CGPoint(x: 0, y: attributes!.frame.origin.y - self.contentInset.top)
        self.setContentOffset(topOfHeader, animated:false)

    }
 }

}

let attributes = layoutAttributesForSupplementaryElement(ofKind: UICollectionElementKindSectionHeader, at: indexPath) 我的应用程序崩溃了,崩溃的原因是:

reason: 'no UICollectionViewLayoutAttributes instance for -layoutAttributesForSupplementaryElementOfKind: UICollectionElementKindSectionHeader at path <NSIndexPath: 0x1564e0b0> {length = 2, path = 18 - 1}'

请告诉我问题是什么以及如何解决 提前致谢:-)

这是因为单元格无法检索布局属性。 layoutAttributesForItemAtIndexPath returns 如果将由更新创建的单元格不可见,则为零。

我认为下面的解决方案适合你。

覆盖 layoutAttributesForItemAtIndexPath 必须使用此方法:

Swift 3.0 头方法,希望对你有帮助

override func layoutAttributesForItemscrollToSection(at_ indexPathsection: IndexPathInt) -> UICollectionViewLayoutAttributes? {
   //set Contentoffset to particular section
}