How do I set collection view's cell size via the auto layout

前端 未结 5 617
逝去的感伤
逝去的感伤 2020-12-05 07:45

Hi I\'m trying to resize the cell via the auto layout.

I want display the cell by the 3 by 3.

First Cell\'s margin left=0

Last Cell\'s m

5条回答
  •  北荒
    北荒 (楼主)
    2020-12-05 08:31

    Great answer by vacawama but I had 2 issues. I wanted the spacing that I defined in storyboard to automatically be used.

    And secondly, I could not get this function to invoke and no one mentioned how? In order to invoke the collectionView's sizeForItemAt you need to extend UICollectionViewDelegateFlowLayout instead of extending UICollectionViewDelegate. I hope this saves someone else some time.

    extension MyViewController: UICollectionViewDelegateFlowLayout, UICollectionViewDataSource {
    
        func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
            let cellsAcross: CGFloat = 3
            var widthRemainingForCellContent = collectionView.bounds.width
            if let flowLayout = collectionViewLayout as? UICollectionViewFlowLayout {
                let borderSize: CGFloat = flowLayout.sectionInset.left + flowLayout.sectionInset.right
                widthRemainingForCellContent -= borderSize + ((cellsAcross - 1) * flowLayout.minimumInteritemSpacing)
            }
            let cellWidth = widthRemainingForCellContent / cellsAcross
            return CGSize(width: cellWidth, height: cellWidth)
        }
    
    }
    

提交回复
热议问题