环境:
UICollectionView
看起来像 UITableView
自定义 UICollectionViewFlowLayout 子类来定义启用frame
的DecorationView
Self-Sizing 单元格
预期行为:
ADecorationView
应该作为每个部分的背景放置UICollectionView
观察到的行为:
折叠DecorationView
到任意大小:
似乎UICollectionView
试图计算DecorationView
. 如果我禁用 Self-Sizing 单元格,则装饰视图将准确放置在预期位置。
有什么方法可以禁用 Self-Sizing forDecorationView
吗?
在我的UICollectionViewFlowLayout
子类中,我只需获取该部分中的第一个和最后一个单元格并拉伸背景以填充它们下方的空间。问题是UICollectionView
不尊重那里计算的大小:
override func layoutAttributesForDecorationView(ofKind elementKind: String, at indexPath: IndexPath) -> UICollectionViewLayoutAttributes? {
guard let collectionView = collectionView else {
return nil
}
let section = indexPath.section
let attrs = UICollectionViewLayoutAttributes(forDecorationViewOfKind: backgroundViewClass.reuseIdentifier(),
with: indexPath)
let numberOfItems = collectionView.numberOfItems(inSection: section)
let lastIndex = numberOfItems - 1
guard let firstItemAttributes = layoutAttributesForItem(at: IndexPath(indexes: [section, 0])),
let lastItemAttributes = layoutAttributesForItem(at: IndexPath(indexes: [section, lastIndex])) else {
return nil
}
let startFrame = firstItemAttributes.frame
let endFrame = lastItemAttributes.frame
let origin = startFrame.origin
let size = CGSize(width: startFrame.width,
height: -startFrame.minY + endFrame.maxY)
let frame = CGRect(origin: origin, size: size)
attrs.frame = frame
attrs.zIndex = -1
return attrs
}