How to make Supplementary View float in UICollectionView as Section Headers do in UITableView plain style

后端 未结 13 702
逝去的感伤
逝去的感伤 2020-11-27 09:35

I\'m struggling to achieve a \"floating section header\" effect with UICollectionView. Something that\'s been easy enough in UITableView (default b

13条回答
  •  一向
    一向 (楼主)
    2020-11-27 10:26

    Here is my take on it, I think it's a lot simpler than what a glimpsed above. The main source of simplicity is that I'm not subclassing flow layout, rather rolling my own layout (much easier, if you ask me).

    Please Note I am assuming you are already capable of implementing your own custom UICollectionViewLayout that will display cells and headers without floating implemented. Once you have that implementation written, only then will the code below make any sense. Again, this is because the OP was asking specifically about the floating headers part.

    a few bonuses:

    1. I am floating two headers, not just one
    2. Headers push previous headers out of the way
    3. Look, swift!

    note:

    1. supplementaryLayoutAttributes contains all header attributes without floating implemented
    2. I am using this code in prepareLayout, since I do all computation upfront.
    3. don't forget to override shouldInvalidateLayoutForBoundsChange to true!

    // float them headers
    let yOffset = self.collectionView!.bounds.minY
    let headersRect = CGRect(x: 0, y: yOffset, width: width, height: headersHeight)
    
    var floatingAttributes = supplementaryLayoutAttributes.filter {
        $0.frame.minY < headersRect.maxY
    }
    
    // This is three, because I am floating 2 headers
    // so 2 + 1 extra that will be pushed away
    var index = 3
    var floatingPoint = yOffset + dateHeaderHeight
    
    while index-- > 0 && !floatingAttributes.isEmpty {
    
        let attribute = floatingAttributes.removeLast()
        attribute.frame.origin.y = max(floatingPoint, attribute.frame.origin.y)
    
        floatingPoint = attribute.frame.minY - dateHeaderHeight
    }
    

提交回复
热议问题