在UICollectionViewFlowLayout子类

时间:2017-05-08 00:37:16

标签: ios uicollectionview uicollectionviewlayout

我有一个UICollectionViewFlowLayout的自定义子类,我正在尝试将单元格大小更新为始终为屏幕的宽度。当我旋转到横向时,单元格没有正确更新。这是我的子类:

// MARK: - Constants

private let EdgeInset: CGFloat = 10
private let CellSpacing: CGFloat = 10
private let LineSpacing: CGFloat = 10
private let CellHeight: CGFloat = 50

// MARK: - FullWidthLayout

class FullWidthLayout: UICollectionViewFlowLayout {

    override init() {
        super.init()
        commonInit()
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        commonInit()
    }

    func commonInit() {
        minimumLineSpacing = LineSpacing
        minimumInteritemSpacing = CellSpacing
        sectionInset = UIEdgeInsets(top: EdgeInset, left: EdgeInset, bottom: EdgeInset, right: EdgeInset)
    }
}

// MARK: Layout Methods

extension FullWidthLayout {

    override func prepare() {
        super.prepare()

        if let view = collectionView {
            let availableWidth = view.bounds.width - EdgeInset * 2
            itemSize = CGSize(width: availableWidth, height: CellHeight)

            print("Item size: \(itemSize)")
        }
    }
}

这是控制台中的输出:

Item size: (300.0, 50.0)
Item size: (548.0, 50.0)

以下是模拟器中发生的事情:

portrait version of my app

landscape version of my app

项目大小似乎在prepare()方法中正确设置,但单元格未在集合视图中更新。如果您从横向开始并移至纵向,则会抛出例外情况。

有什么我想念的吗?在某些情况下,基础UICollectionViewFlowLayout会忽略itemSize吗?

以下是GitHub项目的链接:CollectionViewRotate

0 个答案:

没有答案