How to determine height of UICollectionView with FlowLayout

前端 未结 13 2107
醉话见心
醉话见心 2020-11-28 18:01

I\'ve got an UICollectionView with an UICollectionViewFlowLayout, and i want to calculate its content size (for return in intrinsicContentSiz

13条回答
  •  刺人心
    刺人心 (楼主)
    2020-11-28 18:32

    Swift 4.2, Xcode 10.1, iOS 12.1:

    For some reason, collectionView.contentSize.height was appearing smaller than the resolved height of my collection view. First, I was using an auto-layout constraint relative to 1/2 of the superview's height. To fix this, I changed the constraint to be relative to the "safe area" of the view.

    This allowed me to set the cell height to fill my collection view using collectionView.contentSize.height:

    private func setCellSize() {
        let height: CGFloat = (collectionView.contentSize.height) / CGFloat(numberOfRows)
        let width: CGFloat = view.frame.width - CGFloat(horizontalCellMargin * 2)
    
        let layout = collectionView.collectionViewLayout as! UICollectionViewFlowLayout
        layout.itemSize = CGSize(width: width, height: height)
    }
    

    Before

    After

提交回复
热议问题