我试图实现的效果是一种粘性标题单元格。对我来说,粘性细胞漂浮在其他细胞的顶部是很重要的。有点像这样:
┌──────────┐
│ │
│ Cell 0 │
│ ├┐
└┬─────────┘│
│ Cell 4 │
│ │
└──────────┘
┌──────────┐
│ │
│ Cell 5 │
│ │
└──────────┘
┌──────────┐
│ │
│ Cell 6 │
│ │
└──────────┘
单元格4,5和6通常是可见的,我在UICollectionViewFlowLayout
期间在我的layoutAttributesForElementsInRect:
子类中构建单元格0的属性。我所做的只是调用超级实现,确定我需要添加哪个单元格然后构造UICollectionViewLayoutAttributes(forCellWithIndexPath:)
。然后我将它的zIndex
设置为1
(默认为0
)。
我得到的问题是UICollectionView
似乎总是忽略zIndex
┌──────────┐
│ │
│ Cell 0 │
│┌─────────┴┐
└┤ │
│ Cell 4 │
│ │
└──────────┘
┌──────────┐
│ │
│ Cell 5 │
│ │
└──────────┘
┌──────────┐
│ │
│ Cell 6 │
│ │
└──────────┘
现在我相信可以使用3D变换在视觉上对其进行排序,但这对我不起作用,因为我不希望任何点击进入顶部的单元格。因此,在此示例中,我不希望Cell 4接收针对Cell 0的抽头。
有没有人有任何想法?这是在iOS 8.4上。
在UICollectionViewLayout中设置z索引对我不起作用
我在集合视图控制器的方法中设置了z索引
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
customCell.layer.zPosition = 0;
}
我最好的猜测是布局和控制器之间的东西将z索引设置为奇怪的东西
我创建了一个独立项目,以便删除所有无关的代码。在这个过程中,我认为我找到了自己的解决方案。
override func initialLayoutAttributesForAppearingItemAtIndexPath(itemIndexPath: NSIndexPath) -> UICollectionViewLayoutAttributes?
和
override func finalLayoutAttributesForDisappearingItemAtIndexPath(itemIndexPath: NSIndexPath) -> UICollectionViewLayoutAttributes?
不是也应用新的zIndex
所以我认为这是造成它的原因。
只是想我应该回复解决方案,以防万一搜索到其他人。
由于UIKit错误,更新UICollectionViewLayoutAttributes.zIndex
不起作用。
这段代码可以解决问题:
// In your UICollectionViewCell subclass:
override func apply(_ layoutAttributes: UICollectionViewLayoutAttributes) {
super.apply(layoutAttributes)
layer.zPosition = CGFloat(layoutAttributes.zIndex) // or any zIndex you want to set
}
您需要设置两个值。 z索引和3D变换参数。
class HeaderUnderCellsLayout: UICollectionViewFlowLayout {
override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
guard let attributesArray = super.layoutAttributesForElements(in: rect) else { return nil }
attributesArray.forEach { attributes in
if attributes.representedElementCategory == .supplementaryView && attributes.representedElementKind == UICollectionView.elementKindSectionHeader {
attributes.transform3D = CATransform3DMakeTranslation(0, 0, -10)
attributes.zIndex = -200
}
}
return attributesArray
}
override func layoutAttributesForSupplementaryView(ofKind elementKind: String, at indexPath: IndexPath) -> UICollectionViewLayoutAttributes? {
let attributes = super.layoutAttributesForSupplementaryView(ofKind: elementKind, at: indexPath)
attributes?.transform3D = CATransform3DMakeTranslation(0, 0, -10)
attributes?.zIndex = -200
return attributes
}
}