UICollectionView Cell Spacing based on device screen size

后端 未结 5 1754
眼角桃花
眼角桃花 2020-12-08 01:24

I have implemented a UICollectionView, the cell size is w90 h90. When i run it on iPhone 6 i get the proper spacing between cell but when i do it on iPhone 5s i get more sp

5条回答
  •  春和景丽
    2020-12-08 01:37

    For a slightly more flexible answer

    Allows you to adjust number of columns and spacing, expanding on Zaid Pathan's answer

    // MARK: UICollectionViewDelegateFlowLayout delegate method
    func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize
    {
        let cellSpacing = CGFloat(2) //Define the space between each cell
        let leftRightMargin = CGFloat(20) //If defined in Interface Builder for "Section Insets"
        let numColumns = CGFloat(3) //The total number of columns you want
    
        let totalCellSpace = cellSpacing * (numColumns - 1)
        let screenWidth = UIScreen.mainScreen().bounds.width
        let width = (screenWidth - leftRightMargin - totalCellSpace) / numColumns
        let height = CGFloat(110) //whatever height you want
    
        return CGSizeMake(width, height);
    }
    

提交回复
热议问题