【发布时间】:2015-10-07 11:06:42
【问题描述】:
我正在尝试修改UICollectionViewFlowLayout(垂直滚动),以便将每个节标题放在该节所有项目的左侧(而不是在顶部,这是默认设置)。
也就是说,这是默认行为:
...这就是我想要的:
所以我继承了UICollectionViewFlowLayout:
override func layoutAttributesForElementsInRect(rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
guard let attributesToReturn = super.layoutAttributesForElementsInRect(rect) else {
return nil
}
// Copy to avoid the dreadded "Cached frame mismatch" runtime warning:
var copiedAttributes = [UICollectionViewLayoutAttributes]()
for attribute in attributesToReturn {
copiedAttributes.append(attribute.copy() as! UICollectionViewLayoutAttributes)
}
for attributes in copiedAttributes {
if let kind = attributes.representedElementKind {
// Non nil: It is a supplementary View
if kind == UICollectionElementKindSectionHeader {
// HEADER
var frame = attributes.frame
frame.origin.y = frame.origin.y + frame.size.height
frame.size.width = sectionInset.left
attributes.frame = frame
}
}
else{
// Nil: It is an item
}
}
return copiedAttributes
}
另外,为了更好的措施(?),我采用了协议UICollectionViewDelegateFlowLayout并实现了这个方法(虽然不清楚什么优先。然后,故事板文件中有设置,但是那些似乎被他们的运行时对应物覆盖):
func collectionView(
collectionView: UICollectionView,
layout collectionViewLayout: UICollectionViewLayout,
referenceSizeForHeaderInSection section: Int) -> CGSize {
let left = (collectionViewLayout as! UICollectionViewFlowLayout).sectionInset.left
return CGSizeMake(left, 1)
}
...我成功地将标题降低到其部分的第一行;但是,最初由 header 占用的空间保持打开状态:
...我能做到这一点的唯一方法是将标题视图高度设置为1 并将“剪辑子视图”设置为 false,以便显示标签(如果我将高度设置为 0,则标签未绘制),但这绝对是不是最优雅的解决方案(很可能会中断-说-iOS 9.2)
也就是说,标题的实际高度链接到部分之间的垂直空间:我不能将空间设置为零,同时将标题视图保持在合理的大小以进行显示。
也许我也应该向上移动所有部分项目(与我的标题高度相同的数量)来填补这个洞?
【问题讨论】:
-
你发现了吗?我正在尝试做同样的事情,但对于水平滚动集合视图
-
其实是的。我一直忙于发布答案,但我今天会做。给我几个小时!
-
太棒了!迫不及待想听
标签: ios swift uicollectionview