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

后端 未结 3 516
我寻月下人不归
我寻月下人不归 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:03

    You need not check the device size because we can use the collectionView width to calculate the width of the cell. Using the cell width you can calculate the height as per your need.

    One more thing: You need to use UICollectionViewDelegateFlowLayout & confirm the delegate & implement method below

      func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {
    
       let padding: CGFloat =  50
       let collectionViewSize = collectionView.frame.size.width - padding
    
       return CGSizeMake(collectionViewSize/2, collectionViewSize/2)
    
    }
    

    Update: Swift 4.0

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

    Note: I have answered the question considering the cells are square sized

提交回复
热议问题