ios - 为什么在将 UICollectionViewLayout 分配给 UICollectionView 后,UICollectionViewCells 不再可见?

标签 ios swift uicollectionview uicollectionviewcell uicollectionviewlayout

我的应用程序有一个 UIViewController 类;在这个类中,我连接了一个从 Storyboard 加载的 UICollectionView

我正在使用 UICollectionViewLayout 类创建自定义布局。这是它的样子:

class MyLayout: UICollectionViewLayout {

    override func prepareLayout() {
        super.prepareLayout()
    }

    override func collectionViewContentSize() -> CGSize {
        let attributes = super.collectionViewContentSize()
        return attributes
    }

    override func layoutAttributesForElementsInRect(rect: CGRect) -> [AnyObject]? {
        let attributes = super.layoutAttributesForElementsInRect(rect) as? [UICollectionViewLayoutAttributes]
        return attributes
    }

    override func layoutAttributesForItemAtIndexPath(indexPath:
    NSIndexPath) -> UICollectionViewLayoutAttributes {
        let attributes = super.layoutAttributesForItemAtIndexPath(indexPath)
        return attributes
    }
}

要将 UICollectionViewLayout 分配给 UICollectionView,我使用 UICollectionViewcollectionViewLayout 属性:

myCollectionView.collectionViewLayout = MyLayout()

运行应用程序,UICollectionViewCells 不再可见。不过,它们在分配 UICollectionViewLayout 之前是可见的。我现在只能看到 UICollectionView 的背景。

为什么细胞不再可见?

更新

我仔细查看了我的 UICollectionViewUICollectionViewLayoutAttributes,尤其是 contentSize。我打印出它的值,它似乎等于 (0.0, 0.0)layoutAttributesForElementsInRectattributes 值也等于 nil。绝对是一个危险信号。

Download the project

最佳答案

我认为您几乎可以保持所有内容完全相同。将自定义布局的类类型更改为 UICollectionViewFlowLayout

class myLayout: UICollectionViewFlowLayout {
    //all your code here
}

此外,将 myLayout 更改为 MyLayout 以备不时之需:)

关于ios - 为什么在将 UICollectionViewLayout 分配给 UICollectionView 后,UICollectionViewCells 不再可见?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30078582/

相关文章:

ios - 在同一个 UIImageView 中删除和添加多个图像

ios - 如何在多个类中共享枚举?

ios - 将 ionic 4 项目从 PC 移动到 Mac 时,您需要做一些特别的事情吗?

ios - 更改 tableView 中偶数单元格的背景颜色

ios - UICollectionView 与 UIImageViews 的糟糕表现与核心图像操作图像

ios - 如何控制何时在 iOS 中提示用户推送通知权限

Swift 隐式传递 self 作为引用类型的 inout 参数

arrays - 如何正确设置 for 循环以每侧显示 1 个图像

ios - 我的 Collection View 单元格没有被调用?

ios - 对两个项目使用水平滚动时右对齐 UICollectionView(对于 RTL)