这是我的第一个应用程序。我想像这样实现卡片堆栈。
我为此应用使用 UICollectionView
。并通过 minimumLineSpacing =-20.f
UICollectionViewFlowLayout *collectionViewLayout = (UICollectionViewFlowLayout*)self.collectionView.collectionViewLayout;
collectionViewLayout.sectionInset = UIEdgeInsetsMake(0.f, 0, 0, 0);
collectionViewLayout.minimumLineSpacing = -20.f;
和
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
static NSString *identifier = @"Cell";
CollectionNewCell *cell = (CollectionNewCell *)[collectionView dequeueReusableCellWithReuseIdentifier:identifier forIndexPath:indexPath];
cell.layer.borderWidth=1.0f;
cell.layer.borderColor=[UIColor blueColor].CGColor;
cell.layer.cornerRadius=10.0;
cell.layer.masksToBounds=YES;
cell.backgroundColor=[UIColor redColor];
cell.backgroundView.backgroundColor=[UIColor redColor];
return cell;
}
我发现滚动后,一些单元格与其他单元格重叠(例如:黄线)
我不知道我错了什么。你有什么建议吗?
谢谢。
最佳答案
我知道,这个问题很老了,但答案很简单。
这里的问题是 UICollectionView 不知道您想要如何精确地安排单元格的深度。所以它只显示添加到其他单元格之上的 View 层次结构的最后一个单元格。
要解决此问题,您需要设置正确的单元格 zIndex。为此,您需要使用自定义 UICollectionViewLayout :)
Swift 上的解决方案:
class MyCollectionViewFlowLayout: UICollectionViewFlowLayout {
override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
return super.layoutAttributesForElements(in: rect)?.map { attributes in
// Set cell's zIndex = cell's row, so each next cell will always overlap previous cell.
attributes.zIndex = attributes.indexPath.row
return attributes
}
}
}
如果您不想创建自定义布局,还有另一种解决方案。只需像这样重写单元格的方法 apply(_ layoutAttributes: UICollectionViewLayoutAttributes)
:
class MyCell: UICollectionViewCell {
...
override func apply(_ layoutAttributes: UICollectionViewLayoutAttributes) {
layer.zPosition = CGFloat(layoutAttributes.indexPath.row)
}
...
}
关于ios - UICollectionViewCell 滚动后重叠错乱,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25627203/