使用UICollectionViewFlowLayout模仿UITableView布局

时间:2017-10-17 01:56:09

标签: swift uitableview layout uicollectionview

我一直在尝试使用UICollectionView模仿UITableView布局。到目前为止,我已经得到了这个:

class TableViewLayout: UICollectionViewFlowLayout {
    override init() {
        super.init()

        minimumInteritemSpacing = 0
        minimumLineSpacing = 6
        scrollDirection = .vertical

        estimatedItemSize = UICollectionViewFlowLayoutAutomaticSize
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    override func shouldInvalidateLayout(forBoundsChange newBounds: CGRect) -> Bool {
        let currentBounds = collectionView?.bounds ?? .zero
        return newBounds.width != currentBounds.width
    }

    override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
        guard let attributes = super.layoutAttributesForElements(in: rect) else { return [] }

        let sectionInsets: CGFloat = sectionInset.left + sectionInset.right
        let contentInsets: CGFloat = (collectionView?.contentInset.left ?? 0) + (collectionView?.contentInset.right ?? 0)

        for attribute in attributes where attribute.frame.intersects(rect) {
            attribute.size.width = collectionView!.readableContentGuide.layoutFrame.width - sectionInsets - contentInsets
        }

        return attributes
    }
}

在将设备从横向旋转到纵向之前,哪个工作非常好,之后布局挂起说单元格比实际项目大小更宽。

我在这里错过了一些小事吗?我没有看到突出的任何突出问题。 UILabels的布局非常简单,文本数量不足。他们可以在这里看到

肖像

Portrait

风景

Landscape

横向画像

后出错

Error

0 个答案:

没有答案