iosswiftuicollectionviewsizecgsize

Calculations of the 80% of screen and 20% in UICollectionView


I write function that return size of the cell for the UICollectionView.

   fileprivate func getCellSize(with row: Int) -> CGSize {

        let percentage: CGFloat = row == 0 ? 0.8 : 0.2
        let width = self.collectionView?.frame.width
        let height = self.collectionView?.frame.height

        let expectedWidth = width! * percentage
        let expectedHeight = height! * 0.5

        return CGSize(width: expectedWidth, height: expectedHeight)
    }

This function is working fine but it has small issue that is connected with rounding it seams to me. Because layout that I receive is not fully covered with cells as it is expected.

The result of the function for the iPhone 6 emulator is following:

0: ROW = (533.60000000000002,187.5)

1: ROW = (133.40000000000001,187.5)

Actual result:

enter image description here

Expected result:

enter image description here


Solution

  • How about

    if let frameWidth = self.collectionView?.frame.width {
         let row0Width = Int(Double(frameWidth) * 0.8)
         let otherWidth = frameWidth - row0Width
         let expectedWidth = row == 0 ? row0Width : otherWidth
         // ...
    }
    

    to avoid rounding issues?