Specify row and column number for UICollectionView

前端 未结 5 1695
失恋的感觉
失恋的感觉 2021-01-03 23:25

I want to show a UICollectionView which contains exactly 2 rows and 100 cells in each row.

// 1
- (NSInteger)collectionView:(UICollectionView *)view numberOf         


        
5条回答
  •  北海茫月
    2021-01-03 23:52

    The more general approach to achieve n columns in collection view which is compatible in any orientation is

     func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {
    
       // flow layout have all the important info like spacing, inset of collection view cell, fetch it to find out the attributes specified in xib file
       guard let flowLayout = collectionViewLayout as? UICollectionViewFlowLayout else {
            return CGSize()
        }
    
        // subtract section left/ right insets mentioned in xib view
    
        let widthAvailbleForAllItems =  (collectionView.frame.width - flowLayout.sectionInset.left - flowLayout.sectionInset.right)
    
        // Suppose we have to create nColunmns
        // widthForOneItem achieved by sunbtracting item spacing if any
    
        let widthForOneItem = widthAvailbleForAllItems / nColumns - flowLayout.minimumInteritemSpacing
    
    
        // here height is mentioned in xib file or storyboard
        return CGSize(width: CGFloat(widthForOneItem), height: (flowLayout.itemSize.height))
     }
    

提交回复
热议问题