Setting size of UICollectionViewCell in a way that there is no interim spacing in between

前端 未结 4 1812
时光取名叫无心
时光取名叫无心 2021-01-28 23:36

I\'m using an UICollectionView on which I want to place seven cells side by side. The whole screen should be used for this. Currently, I\'m using the width of the c

4条回答
  •  逝去的感伤
    2021-01-29 00:26

    As you already figured out it's impossible to divide a 320 point wide screen into 7 equal portions.

    But if a cell is a half or even one point larger or smaller than another one nobody will notice. You can use a little bit of math to get integer pixel values (i.e. 0.5 points).

    func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {
        var size: CGSize!
        let column = indexPath.item % 7
        let width = collectionView.bounds.size.width
        let height = 80.0
    
        if width == 320.0 {
            // iPhone 5
            // 46 + 0,5 + 45 + 0,5 + 45 + 0,5 + 45 + 0,5 + 45 + 0,5 + 45 + 0,5 + 46
            if column == 0 || column == 6 {
                size = CGSize(width: 46, height: height)
            }
            else {
                size = CGSize(width: 45, height: height)
            }
        }
        else if width == 375.0 {
            // iPhone 6
            // 53 + 0,5 + 53 + 0,5 + 53 + 0,5 + 54 + 0,5 + 53 + 0,5 + 53 + 0,5 + 53
            if column == 3 {
                size = CGSize(width: 54, height: height)
            }
            else {
                size = CGSize(width: 53, height: height)
            }
        }
        else if width == 414.0 {
            // iPhone 6 Plus
            // 58 + 0,5 + 59 + 0,5 + 59 + 0,5 + 59 + 0,5 + 59 + 0,5 + 59 + 0,5 + 58
            if column == 0 || column == 6 {
                size = CGSize(width: 58, height: height)
            }
            else {
                size = CGSize(width: 59, height: height)
            }
        }
        else {
            println("Unhandled Width: \(width)")
            abort()
        }
        return size
    }
    

    That's just an example, that I had ready because I am currently working on a calendar view. It has a 1 pixel spacing between each cell. For a 320 pt wide cell layout without spacing you could use something like 45.5+45.5+46+46+46+45.5+45.5

提交回复
热议问题