首页 > 解决方案 > UICollectionView 布局在滚动时表现异常

问题描述

我正在设置一个集合视图,以便在 Instagram 上显示内容。Instagram 的网格

为了设置布局,我使用了UIcollectionviewDelegateFlowLayout的一些委托方法:

extension ProfileViewController : UICollectionViewDelegateFlowLayout{

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat{
        return 0
    }


    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat{
        return 0
    }

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        return CGSize(width: (view.frame.width)/3, height: (view.frame.width)/3)
    }
}

当我打开项目时,collectionView 运行良好。当您快速向下滚动 collectionView 以使所有单元格瞬间消失时,就会出现问题。在那一刻,我之前设置的单元格布局不成立,图像变得超级缩放并且彼此重叠,如下所示:混乱的 collectionView 我不知道如何解决这个问题。同样在编译器中我得到这个错误:

the item width must be less than the width of the UICollectionView minus the section insets left and right values, minus the content insets left and right values.

Please check the values returned by the delegate.
The relevant UICollectionViewFlowLayout instance is <UICollectionViewFlowLayout:   0x7fbbe972d1f0>, and it is attached to <UICollectionView: 0x7fbbeb056400; frame = (0 0; 414 896); clipsToBounds = YES; autoresize = RM+BM; 
gestureRecognizers = <NSArray: 0x60000203c4e0>; layer = <CALayer: 0x600002ef19c0>; contentOffset: {0, 424}; contentSize: {414, 16048}; adjustedContentInset: {88, 0, 83, 0}; layout: <UICollectionViewFlowLayout: 0x7fbbe972d1f0>; dataSource: <InstagramClone.ProfileViewController: 0x7fbbe9708890>>.

标签: iosswiftuicollectionviewuicollectionviewdelegateuicollectionviewdelegateflowlayout

解决方案


我认为您的问题可能与本文中的问题相同

尝试通过将 设置UICollectionView's estimatedSize为无来解决您的问题。

这是因为在 Xcode 11 中,CollectionView 中的单元格现在可以使用画布中的自动布局约束视图自行调整大小。


推荐阅读