如何使补充视图在 UICollectionView 中浮动,就像节标题在 UITableView 纯样式中所做的那样 [英] How to make Supplementary View float in UICollectionView as Section Headers do in UITableView plain style
问题描述
我正在努力使用 UICollectionView
实现浮动节标题"效果.在 UITableView
中已经足够简单的东西(UITableViewStylePlain
的默认行为)在 UICollectionView
中似乎不可能没有大量的努力.我错过了明显的吗?
I'm struggling to achieve a "floating section header" effect with UICollectionView
. Something that's been easy enough in UITableView
(default behavior for UITableViewStylePlain
) seems impossible in UICollectionView
without lots of hard work. Am I missing the obvious?
Apple 没有提供有关如何实现这一点的文档.似乎必须继承 UICollectionViewLayout
并实现自定义布局才能实现此效果.这需要相当多的工作,实现以下方法:
Apple provides no documentation on how to achieve this. It seems that one has to subclass UICollectionViewLayout
and implement a custom layout just to achieve this effect. This entails quite a bit of work, implementing the following methods:
覆盖方法
每个布局对象都应该实现以下方法:
Every layout object should implement the following methods:
collectionViewContentSize
layoutAttributesForElementsInRect:
layoutAttributesForItemAtIndexPath:
layoutAttributesForSupplementaryViewOfKind:atIndexPath: (if your layout supports supplementary views)
layoutAttributesForDecorationViewOfKind:atIndexPath: (if your layout supports decoration views)
shouldInvalidateLayoutForBoundsChange:
但是,我不清楚如何使补充视图浮动在单元格上方并粘"到视图的顶部,直到到达下一部分.在布局属性中是否有一个标志?
However its not clear to me how to make the supplementary view float above the cells and "stick" to the top of the view until the next section is reached. Is there a flag for this in the layout attributes?
我本来会使用 UITableView
但我需要创建一个相当复杂的集合层次结构,这可以通过集合视图轻松实现.
I would have used UITableView
but I need to create a rather complex hierarchy of collections which is easily achieved with a collection view.
任何指导或示例代码将不胜感激!
Any guidance or sample code would be greatly appreciated!
推荐答案
在 iOS9 中,Apple 很友好地在 UICollectionViewFlowLayout
称为 sectionHeadersPinToVisibleBounds
.
In iOS9, Apple was kind enough to add a simple property in UICollectionViewFlowLayout
called sectionHeadersPinToVisibleBounds
.
有了这个,你可以让标题像在表格视图中一样浮动.
With this, you can make the headers float like that in table views.
let layout = UICollectionViewFlowLayout()
layout.sectionHeadersPinToVisibleBounds = true
layout.minimumInteritemSpacing = 1
layout.minimumLineSpacing = 1
super.init(collectionViewLayout: layout)
这篇关于如何使补充视图在 UICollectionView 中浮动,就像节标题在 UITableView 纯样式中所做的那样的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!