extension UICollectionView {
    public func scrollToSection(section: Int, animated: Bool) {

        guard numberOfSections > section else {
            return
        }

        guard numberOfItems(inSection: section) > 0 else {
            return
        }

        let sectionY: CGFloat = { () -> CGFloat in

            let indexPath = IndexPath(item: 0, section: section)

            let top: CGFloat = 0

            guard let attributes = layoutAttributesForItem(at: indexPath) else {
                return top
            }

            switch attributes.representedElementCategory {
            case .cell, .decorationView:
                return top
                
            case .supplementaryView:
                guard let attributes = layoutAttributesForSupplementaryElement(ofKind: UICollectionView.elementKindSectionHeader, at: indexPath) else {
                    return top
                }

                return attributes.frame.origin.y
            @unknown default:
                return top
            }
        }()

        var offsetY: CGFloat = sectionY - contentInset.top

        if #available(iOS 11.0, *) {
            offsetY -= safeAreaInsets.top
        }

        let offset = CGPoint(x: 0, y: offsetY)
        setContentOffset(offset, animated: animated)
    }
}


避免不同Layout或是沒有header的時候,在iOS 10發生Crash

全站熱搜

小賢 發表在 痞客邦 留言(0) 人氣()