SoFunction
Updated on 2025-04-09

iOS solves the problem of UICollectionView calculating Cell size

Preface

The problems caused by unfamiliarity in the API, and if you take it for granted, you will indeed have problems. Here I will record the UICollectionView usage problems.

text

Trap 1:minimumLineSpacing、minimumInteritemSpacing

It is easy to set these two properties to 0. These two properties are the minimum row spacing and the minimum column spacing. Note that it is the smallest! ! In other words, it can actually be > 0, either the spacing is 0

Trap Two:sectionInset

Sets the margins of the cell. At first I thought that the margins of each cell would have superimposed effects between adjacent cells, but in fact it is not the case. This property only ensures the spacing between adjacent cells and does not superimpose them! !

After understanding the above two traps, we can accurately calculate the size of the Cell, and then set the size of the itemSize to be correct. For example:

 let ITEM_MIN_WIDTH: CGFloat = 300
  let ITEM_SPACING: CGFloat = 6

  func resizeCollectionView(size: CGSize) {
    if let layout = collectionView?.collectionViewLayout as? UICollectionViewFlowLayout {
       = ITEM_SPACING
       = ITEM_SPACING

      var itemCount = Int( / ITEM_MIN_WIDTH)
      if itemCount == 0 {
        itemCount = 1
      }

      if itemCount == 1 {
         = CGSizeMake(,  * 10 / 16)
         = UIEdgeInsetsMake(6, 0, 0, 0)
      } else {
        let width = ( - CGFloat((itemCount + 1)) * ITEM_SPACING) / CGFloat(itemCount)
         = CGSizeMake(width, width * 10 / 16)
         = UIEdgeInsetsMake(ITEM_SPACING, ITEM_SPACING, 0, ITEM_SPACING)
      }
      collectionView?.layoutIfNeeded()
    }
  }

Code description:

Pass in the size of the current view and dynamically calculate the cell size, which can be conveniently adapted to iPhone/iPad. The edges on both sides are hidden in single columns, and the gaps on both sides are displayed when multiple columns are displayed.

The above is the usage and explanation of IOS UICollectionView. I hope it can help friends who develop IOS.