ios - UICollectionViewCell 滚动后重叠错乱

标签 ios objective-c uicollectionview uicollectionviewcell uicollectionviewlayout

这是我的第一个应用程序。我想像这样实现卡片堆栈。

enter image description here

我为此应用使用 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;
}

我发现滚动后,一些单元格与其他单元格重叠(例如:黄线)

enter image description here

我不知道我错了什么。你有什么建议吗?

谢谢。

最佳答案

我知道,这个问题很老了,但答案很简单。

这里的问题是 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/

相关文章:

ios - iOS 上 CodenameOne 中图形的一些问题

ios - Xcode 7 大小类问题?

ios - 在 tableView : willDisplayHeaderView: forSection: 的 UITableViewHeaderFooterView 中垂直居中 textLabel

ios - reloadItemsAtIndexPaths 上的 Collection View 崩溃

ios - 在 swift4 中移动 View 时屏幕是黑色的

iphone - 从 Windows 与 iOS 对话?

ios - 重新加载 UICollectionView 部分并保留滚动位置

objective-c - MKMapView 和注释隐藏缩放

ios - 具有不同单元格数量的 viewController 中的多个 Collection View

swift - 点击按钮(位于 UICollectionViewController 中)时如何激活共享扩展(UIActivityViewController)?