如何在UICollectionView中将Supplementary View float作为Section Headers在UITableView普通样式中进行

时间:2012-11-22 11:25:12

标签: iphone uitableview view uicollectionview supplementary

我正在努力实现一个"浮动部分标题"效果UICollectionViewUITableView UITableViewStylePlain的默认行为在UICollectionView中似乎是不可能的,没有大量的努力工作。我错过了明显的吗?

Apple没有提供有关如何实现此目标的文档。似乎必须将UICollectionViewLayout子类化并实现自定义布局才能实现此效果。这需要相当多的工作,实现以下方法:

覆盖方法

每个布局对象都应实现以下方法:

collectionViewContentSize
layoutAttributesForElementsInRect:
layoutAttributesForItemAtIndexPath:
layoutAttributesForSupplementaryViewOfKind:atIndexPath: (if your layout supports supplementary views)
layoutAttributesForDecorationViewOfKind:atIndexPath: (if your layout supports decoration views)
shouldInvalidateLayoutForBoundsChange:

然而,我不清楚如何使补充视图漂浮在细胞上方并且"坚持"到达视图的顶部,直到到达下一部分。布局属性中是否有这样的标志?

我会使用UITableView但我需要创建一个相当复杂的集合层次结构,这可以通过集合视图轻松实现。

非常感谢任何指导或示例代码!

13 个答案:

答案 0 :(得分:64)

在iOS9中,Apple非常友好地在名为UICollectionViewFlowLayoutsectionHeadersPinToVisibleBounds中添加了一个简单的属性。

通过这种方式,您可以使表头视图中的标题浮动。

let layout = UICollectionViewFlowLayout()
layout.sectionHeadersPinToVisibleBounds = true
layout.minimumInteritemSpacing = 1
layout.minimumLineSpacing = 1
super.init(collectionViewLayout: layout)

答案 1 :(得分:47)

实现以下委托方法:

– collectionView:layout:sizeForItemAtIndexPath:
– collectionView:layout:insetForSectionAtIndex:
– collectionView:layout:minimumLineSpacingForSectionAtIndex:
– collectionView:layout:minimumInteritemSpacingForSectionAtIndex:
– collectionView:layout:referenceSizeForHeaderInSection:
– collectionView:layout:referenceSizeForFooterInSection:

在具有:cellForItemAtIndexPath方法的视图控制器中(只返回正确的值)。或者,您也可以直接在布局对象中设置这些值,而不是使用委托方法。 [layout setItemSize:size];

使用这些方法中的任何一种都可以让您在设置自定义布局时删除代码而不是IB中的设置。请务必将<UICollectionViewDelegateFlowLayout>添加到您的.h文件中!

创建一个UICollectionViewFlowLayout的新子类,随意调用它,并确保H文件具有:

#import <UIKit/UIKit.h>

@interface YourSubclassNameHere : UICollectionViewFlowLayout

@end

在实施文件中确保它具有以下内容:

- (NSArray *) layoutAttributesForElementsInRect:(CGRect)rect {

    NSMutableArray *answer = [[super layoutAttributesForElementsInRect:rect] mutableCopy];
    UICollectionView * const cv = self.collectionView;
    CGPoint const contentOffset = cv.contentOffset;

    NSMutableIndexSet *missingSections = [NSMutableIndexSet indexSet];
    for (UICollectionViewLayoutAttributes *layoutAttributes in answer) {
        if (layoutAttributes.representedElementCategory == UICollectionElementCategoryCell) {
            [missingSections addIndex:layoutAttributes.indexPath.section];
        }
    }
    for (UICollectionViewLayoutAttributes *layoutAttributes in answer) {
        if ([layoutAttributes.representedElementKind isEqualToString:UICollectionElementKindSectionHeader]) {
            [missingSections removeIndex:layoutAttributes.indexPath.section];
        }
    }

    [missingSections enumerateIndexesUsingBlock:^(NSUInteger idx, BOOL *stop) {

        NSIndexPath *indexPath = [NSIndexPath indexPathForItem:0 inSection:idx];

        UICollectionViewLayoutAttributes *layoutAttributes = [self layoutAttributesForSupplementaryViewOfKind:UICollectionElementKindSectionHeader atIndexPath:indexPath];

        [answer addObject:layoutAttributes];

    }];

    for (UICollectionViewLayoutAttributes *layoutAttributes in answer) {

        if ([layoutAttributes.representedElementKind isEqualToString:UICollectionElementKindSectionHeader]) {

            NSInteger section = layoutAttributes.indexPath.section;
            NSInteger numberOfItemsInSection = [cv numberOfItemsInSection:section];

            NSIndexPath *firstCellIndexPath = [NSIndexPath indexPathForItem:0 inSection:section];
            NSIndexPath *lastCellIndexPath = [NSIndexPath indexPathForItem:MAX(0, (numberOfItemsInSection - 1)) inSection:section];

            NSIndexPath *firstObjectIndexPath = [NSIndexPath indexPathForItem:0 inSection:section];
            NSIndexPath *lastObjectIndexPath = [NSIndexPath indexPathForItem:MAX(0, (numberOfItemsInSection - 1)) inSection:section];

            UICollectionViewLayoutAttributes *firstObjectAttrs;
            UICollectionViewLayoutAttributes *lastObjectAttrs;

            if (numberOfItemsInSection > 0) {
                firstObjectAttrs = [self layoutAttributesForItemAtIndexPath:firstObjectIndexPath];
                lastObjectAttrs = [self layoutAttributesForItemAtIndexPath:lastObjectIndexPath];
            } else {
                firstObjectAttrs = [self layoutAttributesForSupplementaryViewOfKind:UICollectionElementKindSectionHeader
                                                                    atIndexPath:firstObjectIndexPath];
                lastObjectAttrs = [self layoutAttributesForSupplementaryViewOfKind:UICollectionElementKindSectionFooter
                                                                   atIndexPath:lastObjectIndexPath];
            }

            CGFloat headerHeight = CGRectGetHeight(layoutAttributes.frame);
            CGPoint origin = layoutAttributes.frame.origin;
            origin.y = MIN(
                           MAX(
                               contentOffset.y + cv.contentInset.top,
                               (CGRectGetMinY(firstObjectAttrs.frame) - headerHeight)
                               ),
                           (CGRectGetMaxY(lastObjectAttrs.frame) - headerHeight)
                           );

            layoutAttributes.zIndex = 1024;
            layoutAttributes.frame = (CGRect){
                .origin = origin,
                .size = layoutAttributes.frame.size
            };

        }

    }

    return answer;

}

- (BOOL) shouldInvalidateLayoutForBoundsChange:(CGRect)newBound {

    return YES;

}

在Interface Builder中为Flow Layout选择“Custom”,选择刚刚创建的“YourSubclassNameHere”类。跑吧!

(注意:上面的代码可能不尊重contentInset.bottom值,或者特别是大或小的页脚对象,或者具有0个对象但没有页脚的集合。)

答案 2 :(得分:7)

以下是我对它的看法,我认为它比上面的瞥见简单得多。简单的主要来源是我没有对流程布局进行子类化,而是滚动我自己的布局(如果你问我的话,会更容易)。

请注意我假设您已经能够实现自己的自定义UICollectionViewLayout,它将显示没有浮动实现的单元格和标题。一旦你编写了实现,只有这样,下面的代码才有意义。同样,这是因为OP专门询问浮动标题部分。

一些奖金:

  1. 我正在浮动两个标题,而不只是一个
  2. 标题推送前一个标题
  3. 看,swift!
  4. 请注意:

    1. supplementaryLayoutAttributes包含所有未实现浮动的标头属性
    2. 我在prepareLayout中使用此代码,因为我提前完成所有计算。
    3. 请勿忘记将shouldInvalidateLayoutForBoundsChange覆盖为true!

    4. // 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
      }
      

答案 3 :(得分:6)

如果您有一个标题视图要固定到UICollectionView的顶部,这是一个相对简单的方法。请注意,这意味着尽可能简单 - 它假设您在单个部分中使用单个标头。

//Override UICollectionViewFlowLayout class
@interface FixedHeaderLayout : UICollectionViewFlowLayout
@end

@implementation FixedHeaderLayout
//Override shouldInvalidateLayoutForBoundsChange to require a layout update when we scroll 
- (BOOL) shouldInvalidateLayoutForBoundsChange:(CGRect)newBounds {
    return YES;
}

//Override layoutAttributesForElementsInRect to provide layout attributes with a fixed origin for the header
- (NSArray *) layoutAttributesForElementsInRect:(CGRect)rect {

    NSMutableArray *result = [[super layoutAttributesForElementsInRect:rect] mutableCopy];

    //see if there's already a header attributes object in the results; if so, remove it
    NSArray *attrKinds = [result valueForKeyPath:@"representedElementKind"];
    NSUInteger headerIndex = [attrKinds indexOfObject:UICollectionElementKindSectionHeader];
    if (headerIndex != NSNotFound) {
        [result removeObjectAtIndex:headerIndex];
    }

    CGPoint const contentOffset = self.collectionView.contentOffset;
    CGSize headerSize = self.headerReferenceSize;

    //create new layout attributes for header
    UICollectionViewLayoutAttributes *newHeaderAttributes = [UICollectionViewLayoutAttributes layoutAttributesForSupplementaryViewOfKind:UICollectionElementKindSectionHeader withIndexPath:[NSIndexPath indexPathForItem:0 inSection:0]];
    CGRect frame = CGRectMake(0, contentOffset.y, headerSize.width, headerSize.height);  //offset y by the amount scrolled
    newHeaderAttributes.frame = frame;
    newHeaderAttributes.zIndex = 1024;

    [result addObject:newHeaderAttributes];

    return result;
}
@end

请参阅:https://gist.github.com/4613982

答案 4 :(得分:4)

如果已经在StoryboardXib文件中设置了流量布局,请尝试使用

(collectionView.collectionViewLayout as? UICollectionViewFlowLayout)?.sectionHeadersPinToVisibleBounds = true

答案 5 :(得分:3)

如果有人在Objective-C中寻找解决方案,请将其放在viewDidload:

INSERT INTO PurchaseInfo (ContactName) VALUES ('Contact Name Andy');

答案 6 :(得分:3)

@iPrabu与sectionHeadersPinToVisibleBounds有一个excellent answer。我要补充一下,您也可以在Interface Builder中设置此属性:

  1. 在文档导航器中选择流布局对象。 (如果已折叠,请先使用编辑器左下角的工具栏按钮将其展开。)

Selecting the flow layout object in the document navigator.

  1. 打开身份检查器,并添加一个具有键路径sectionHeadersPinToVisibleBounds的用户定义的运行时属性,键入 Boolean ,然后选中此复选框。

Setting the runtime attribute in the Identity inspector.

默认标题视图具有透明背景。您可能要使其(部分)不透明或添加模糊效果视图。

答案 7 :(得分:2)

我遇到了同样的问题,并在我的谷歌搜索结果中发现了这个问题。首先,我要感谢cocotutch分享他的解决方案。但是,我希望我的UICollectionView能够水平滚动并且标题会粘在屏幕的左边,所以我不得不稍微更改一下。

基本上我只是改变了这个:

        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
        };

到此:

        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
            };
        }

请参阅:https://gist.github.com/vigorouscoding/5155703http://www.vigorouscoding.com/2013/03/uicollectionview-with-sticky-headers/

答案 8 :(得分:2)

我用强力编码的代码运行了这个。 但是,该代码不考虑sectionInset。

所以我更改了垂直滚动的代码

origin.y = MIN(
              MAX(contentOffset.y, (CGRectGetMinY(firstCellAttrs.frame) - headerHeight)),
              (CGRectGetMaxY(lastCellAttrs.frame) - headerHeight)
           );

origin.y = MIN(
           MAX(contentOffset.y, (CGRectGetMinY(firstCellAttrs.frame) - headerHeight - self.sectionInset.top)),
           (CGRectGetMaxY(lastCellAttrs.frame) - headerHeight + self.sectionInset.bottom)
           );

如果你们想要水平滚动代码,请参阅代码aove。

答案 9 :(得分:1)

我在github上添加了一个非常简单的示例。

基本上,策略是提供一个自定义布局,使边界变化无效,并为拥抱当前边界的补充视图提供布局属性。正如其他人所说。我希望代码很有用。

答案 10 :(得分:1)

cocotouch的帖子中有一个错误。当部分中没有项目并且部分页脚设置为不显示时,部分标题将超出集合视图,用户将无法看到它。

实际上改变了:

if (numberOfItemsInSection > 0) {
    firstObjectAttrs = [self layoutAttributesForItemAtIndexPath:firstObjectIndexPath];
    lastObjectAttrs = [self layoutAttributesForItemAtIndexPath:lastObjectIndexPath];
} else {
    firstObjectAttrs = [self layoutAttributesForSupplementaryViewOfKind:UICollectionElementKindSectionHeader
                                                            atIndexPath:firstObjectIndexPath];
    lastObjectAttrs = [self layoutAttributesForSupplementaryViewOfKind:UICollectionElementKindSectionFooter
                                                           atIndexPath:lastObjectIndexPath];
}

成:

if (numberOfItemsInSection > 0) {
    firstObjectAttrs = [self layoutAttributesForItemAtIndexPath:firstObjectIndexPath];
    lastObjectAttrs = [self layoutAttributesForItemAtIndexPath:lastObjectIndexPath];
} else {
    firstObjectAttrs = [self layoutAttributesForSupplementaryViewOfKind:UICollectionElementKindSectionHeader
                                                            atIndexPath:firstObjectIndexPath];
    lastObjectAttrs = [self layoutAttributesForSupplementaryViewOfKind:UICollectionElementKindSectionFooter
                                                           atIndexPath:lastObjectIndexPath];
    if (lastObjectAttrs == nil) {
        lastObjectAttrs = firstObjectAttrs;
    }
}

将解决此问题。

答案 11 :(得分:0)

VCollectionViewGridLayout执行粘贴标头。它是基于TLIndexPathTools的垂直滚动简单网格布局。尝试运行Sticky Headers示例项目。

此布局还具有比UICollectionViewFlowLayout更好的批量更新动画行为。提供了几个示例项目,允许您在两个布局之间切换以演示改进。

答案 12 :(得分:0)

Swift 5.0

在viewDidLoad中放置以下内容:

if let layout = collectionView?.collectionViewLayout as? UICollectionViewFlowLayout {
    layout.sectionHeadersPinToVisibleBounds = true
}