Display just two columns, with multiple rows in a CollectionView using storyboard

后端 未结 3 417
我寻月下人不归
我寻月下人不归 2021-02-01 04:41

I want to display only two cells in a row, no matter what the iPhone screen size is. Like,

My storyboard contains a UICollectionView,connected by constrain

3条回答
  •  深忆病人
    2021-02-01 05:17

    Xcode 8: Swift 3

    I know this is an older question, but I found a few issues with accepted answer.

    I had to use UICollectionViewDelegateFlowLayout which is not CollectionViewFlowLayout

    Then

    In it 'Padding' is of type Int and when you try to subtract it from the variable collectionViewSize it throws an error because they are different types. Very easy to fix however.

    I just added : CGFloat to the line

    Finally, while there is probably a better way to do it, I had to match the padding by adjusting the collectionView leading and trailing constraints.

    So all in all this is what my code ended up looking like

    extension LandingPageViewController: UICollectionViewDelegateFlowLayout {
    
      func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
    
        let padding: CGFloat = 25
        let collectionCellSize = collectionView.frame.size.width - padding
    
      return CGSize(width: collectionCellSize/2, height: collectionCellSize/2)
    
       }
    
    }
    

提交回复
热议问题