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

后端 未结 13 614
逝去的感伤
逝去的感伤 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:35

    I ran into the same problem and found this in my google results. First I would like to thank cocotutch for sharing his solution. However, I wanted my UICollectionView to scroll horizontally and the headers to stick to the left of the screen, so I had to change the solution a bit.

    Basically I just changed this:

            CGFloat headerHeight = CGRectGetHeight(layoutAttributes.frame);
            CGPoint origin = layoutAttributes.frame.origin;
            origin.y = MIN(
                           MAX(
                               contentOffset.y,
                               (CGRectGetMinY(firstCellAttrs.frame) - headerHeight)
                               ),
                           (CGRectGetMaxY(lastCellAttrs.frame) - headerHeight)
                           );
    
            layoutAttributes.zIndex = 1024;
            layoutAttributes.frame = (CGRect){
                .origin = origin,
                .size = layoutAttributes.frame.size
            };
    

    to this:

            if (self.scrollDirection == UICollectionViewScrollDirectionVertical) {
                CGFloat headerHeight = CGRectGetHeight(layoutAttributes.frame);
                CGPoint origin = layoutAttributes.frame.origin;
                origin.y = MIN(
                               MAX(contentOffset.y, (CGRectGetMinY(firstCellAttrs.frame) - headerHeight)),
                               (CGRectGetMaxY(lastCellAttrs.frame) - headerHeight)
                               );
    
                layoutAttributes.zIndex = 1024;
                layoutAttributes.frame = (CGRect){
                    .origin = origin,
                    .size = layoutAttributes.frame.size
                };
            } else {
                CGFloat headerWidth = CGRectGetWidth(layoutAttributes.frame);
                CGPoint origin = layoutAttributes.frame.origin;
                origin.x = MIN(
                               MAX(contentOffset.x, (CGRectGetMinX(firstCellAttrs.frame) - headerWidth)),
                               (CGRectGetMaxX(lastCellAttrs.frame) - headerWidth)
                               );
    
                layoutAttributes.zIndex = 1024;
                layoutAttributes.frame = (CGRect){
                    .origin = origin,
                    .size = layoutAttributes.frame.size
                };
            }
    

    See: https://gist.github.com/vigorouscoding/5155703 or http://www.vigorouscoding.com/2013/03/uicollectionview-with-sticky-headers/

    0 讨论(0)
提交回复
热议问题