前景
公司項目內(nèi)有個小效果涂炎,頁面內(nèi)有不同樣式的分組医吊,其中包含普通列表和瀑布流挠日,切縱向滑動需要將組header置頂,這里的置頂有可能是兩種view弧关,一個是滑動到第幾組之后有一個常駐置頂盅安,以及之后每組內(nèi)容的header置頂, 簡單畫了一個示意圖
下圖中世囊,紅色位置是sectionHeader,需要根據(jù)滑動過程中動態(tài)置頂别瞭,
綠色框內(nèi)容是當滑動到位置后常駐置頂?shù)?br>
黃色框就是不同分組內(nèi)的內(nèi)容
下面直接上代碼
PinCollectionLayout.swift
protocol PinCollectionLayoutDelegate: NSObjectProtocol {
func pinCollectionLayout_scrollDidScroll(section: Int)
func pinCollectionLayout_itemSize(at indexPath: IndexPath) -> CGSize?
func pinCollectionLayout_horItemSpacing(at indexPath: IndexPath) -> CGFloat?
func pinCollectionLayout_verItemSpacing(at indexPath: IndexPath) -> CGFloat?
func pinCollectionLayout_sectionInset(at section: Int) -> UIEdgeInsets
func pinCollectionLayout_column(at section: Int) -> Int
}
class PinCollectionLayout: UICollectionViewFlowLayout {
var pinSection = 0
var maxWidth = UIDevice.isIPad() ? Scale(560) : ScreenWidth
private var left: CGFloat = 0
weak var delegate: PinCollectionLayoutDelegate? = nil
private var pinAttribute: UICollectionViewLayoutAttributes?
private var results: [UICollectionViewLayoutAttributes] = []
private var lastPinMaxBoundryY: CGFloat = 0
private var lastPinMinBoundryY: CGFloat = 0
private var sectionHeights: [[CGFloat]] = []
private var sectionAttributes: [UICollectionViewLayoutAttributes?] = []
//邊界發(fā)生變化時是否重新布局(視圖滾動的時候也會調(diào)用)
override func shouldInvalidateLayout(forBoundsChange newBounds: CGRect) -> Bool {
return true
}
override func prepare() {
super.prepare()
results.removeAll()
let maxWidth = self.maxWidth > 0 ? self.maxWidth : (collectionView?.width ?? ScreenWidth)
left = ((collectionView?.width ?? ScreenWidth) - maxWidth) / 2
if let sections = collectionView?.numberOfSections {
if sectionAttributes.isEmpty {
sectionAttributes = Array.init(repeating: nil, count: sections)
}
sectionHeights = Array.init(repeating: [], count: sections)
for i in 0..<sections {
if let sectionInsets = self.delegate?.pinCollectionLayout_sectionInset(at: i) {
left = sectionInsets.left
} else {
left = ((collectionView?.width ?? ScreenWidth) - maxWidth) / 2
}
let column = self.delegate?.pinCollectionLayout_column(at: i) ?? 1
var top: CGFloat = 0
if i > 0 {
top = sectionHeights[i-1].max() ?? 0
if let sectionInsets = self.delegate?.pinCollectionLayout_sectionInset(at: i - 1) {
top += sectionInsets.bottom
}
}
let indexPath = IndexPath.init(row: 0, section: i)
if let att = super.layoutAttributesForSupplementaryView(ofKind: UICollectionView.elementKindSectionHeader, at: indexPath) {
top += att.frame.size.height
if let sectionInsets = self.delegate?.pinCollectionLayout_sectionInset(at: i) {
top += sectionInsets.top
}
}
sectionHeights[i] = Array.init(repeating: top, count: column)
if let rows = collectionView?.numberOfItems(inSection: i) {
for j in 0..<rows {
let indexPath = IndexPath.init(row: j, section: i)
if let att = self.layoutAttributesForItem(at: indexPath) {
results.append(att)
}
}
if let att = self.layoutAttributesForSupplementaryView(ofKind: UICollectionView.elementKindSectionHeader, at: indexPath) {
results.append(att)
}
}
}
}
}
override func layoutAttributesForItem(at indexPath: IndexPath) -> UICollectionViewLayoutAttributes? {
let column = self.delegate?.pinCollectionLayout_column(at: indexPath.section) ?? 1
let index = indexPath.row % column
let cellSize = self.delegate?.pinCollectionLayout_itemSize(at: indexPath) ?? itemSize
let maxWidth = self.maxWidth > 0 ? self.maxWidth : (collectionView?.width ?? ScreenWidth)
var leftSpace: CGFloat = 0
if let sectionInsets = self.delegate?.pinCollectionLayout_sectionInset(at: indexPath.section) {
leftSpace = sectionInsets.left
} else {
leftSpace = ((collectionView?.width ?? ScreenWidth) - maxWidth) / 2
}
if left + cellSize.width > (leftSpace + maxWidth) {
left = leftSpace
}
let spacing: CGFloat = self.delegate?.pinCollectionLayout_horItemSpacing(at: indexPath) ?? 0
let attr = UICollectionViewLayoutAttributes(forCellWith: indexPath)
attr.frame = CGRectMake(left, sectionHeights[indexPath.section][index], cellSize.width, cellSize.height)
let verSpace: CGFloat = self.delegate?.pinCollectionLayout_verItemSpacing(at: indexPath) ?? 0
sectionHeights[indexPath.section][index] += (cellSize.height + verSpace)
if index < column - 1 {
left += cellSize.width + spacing
} else {
left += cellSize.width
}
return attr
}
//所有元素的位置屬性
override func layoutAttributesForElements(in rect: CGRect)
-> [UICollectionViewLayoutAttributes]? {
return results
}
override var collectionViewContentSize: CGSize {
let maxHeight = self.sectionHeights.last?.max() ?? 0
return CGSizeMake(self.collectionView?.width ?? 0, maxHeight)
}
//補充視圖的布局屬性(這里處理實現(xiàn)粘性分組頭,讓分組頭始終處于分組可視區(qū)域的頂部)
override func layoutAttributesForSupplementaryView(ofKind elementKind: String,
at indexPath: IndexPath) -> UICollectionViewLayoutAttributes? {
var layoutAttributes: UICollectionViewLayoutAttributes?
if let att = self.sectionAttributes[indexPath.section] {
layoutAttributes = att
} else if let l = super.layoutAttributesForSupplementaryView(ofKind: elementKind, at: indexPath) {//先從父類獲取補充視圖的布局屬性
layoutAttributes = l
}
guard let layoutAttributes = layoutAttributes else { return nil }
//如果不是頭部視圖則直接返回
if elementKind != UICollectionView.elementKindSectionHeader {
return layoutAttributes
}
//根據(jù)section索引,獲取對應的邊界范圍
guard let boundaries = boundaries(forSection: indexPath.section) else {
return layoutAttributes
}
guard let collectionView = collectionView else {
return layoutAttributes
}
self.sectionAttributes[indexPath.section] = layoutAttributes
//保存視圖內(nèi)入垂直方向的偏移量
let contentOffsetY = collectionView.contentOffset.y
//補充視圖的frame
var frameForSupplementaryView = layoutAttributes.frame
//計算分組頭垂直方向的最大最小值
let minimum = boundaries.minimum
let maximum = boundaries.maximum - frameForSupplementaryView.height
//如果內(nèi)容區(qū)域的垂直偏移量小于分組頭最小的位置茸习,則將分組頭置于其最小位置
var pinOffset: CGFloat = 0
if indexPath.section > pinSection, let pin = self.pinAttribute {
pinOffset = pin.frame.size.height
}
if contentOffsetY < minimum - pinOffset {
frameForSupplementaryView.origin.y = minimum
lastPinMinBoundryY = minimum
}
//如果內(nèi)容區(qū)域的垂直偏移量大于分組頭最大的位置畜隶,則將分組頭置于其最大位置
else if contentOffsetY > maximum - pinOffset {
frameForSupplementaryView.origin.y = maximum - pinOffset - 1
lastPinMaxBoundryY = maximum + pinOffset
}
//如果都不滿足,則說明內(nèi)容區(qū)域的垂直便宜量落在分組頭的邊界范圍內(nèi)号胚。
//將分組頭設置為內(nèi)容偏移量籽慢,從而讓分組頭固定在集合視圖的頂部
else {
frameForSupplementaryView.origin.y = contentOffsetY + pinOffset - 1
self.delegate?.pinCollectionLayout_scrollDidScroll(section: indexPath.section)
}
if indexPath.section == pinSection {
if contentOffsetY > frameForSupplementaryView.origin.y {
frameForSupplementaryView.origin.y = contentOffsetY
}
self.pinAttribute = layoutAttributes
self.pinAttribute?.zIndex = 1000 //將置頂sectionheader放到最上層視圖
}
//更新布局屬性并返回
let maxWidth = self.maxWidth > 0 ? self.maxWidth : collectionView.width
frameForSupplementaryView.origin.x = (collectionView.width - maxWidth) / 2
frameForSupplementaryView.size.width = maxWidth
layoutAttributes.frame = frameForSupplementaryView
return layoutAttributes
}
//根據(jù)section索引,獲取對應的邊界范圍(返回一個元組)
func boundaries(forSection section: Int) -> (minimum: CGFloat, maximum: CGFloat)? {
var min:CGFloat = 0
if section > 0 {
min = (sectionHeights[section - 1].max() ?? 0) - headerReferenceSize.height
}
let max: CGFloat = (sectionHeights[section].max() ?? 0) - headerReferenceSize.height
//返回最終的邊界值
return (minimum: min, maximum: max)
}
}
extension PinCollectionLayout {
func scrollToSection(at section: Int, animated: Bool) {
var offset: CGFloat = 0
if section > 0, sectionHeights.count > section {
offset = sectionHeights[section - 1].max() ?? 0
}
let indexPath = IndexPath.init(row: 0, section: section)
offset -= ((pinAttribute?.frame.size.height ?? 0))
self.collectionView?.setContentOffset(CGPoint.init(x: 0, y: offset + 1), animated: animated)
}
}