iOS solves the problem of UICollectionView calculating the size of Cell

  • 2020-06-19 11:45:37
  • OfStack

preface

API is not familiar with the problems caused by it, so it is taken for granted that there will be problems if we understand it. Here is a record of the problems of UICollectionView use.

The body of the

Trap 1: minimumLineSpacing, minimumInteritemSpacing

It's easy to set these two properties to 0, the two properties are the minimum row spacing and the minimum column spacing, note the minimum!! In other words, it actually can > Zero, not the spacing is zero

Trap 2: sectionInset

Set the margins of cell. 1. At first, I thought it was the margin of each cell, and there would be a superposition effect between the adjacent ones. In fact, this is not the case.

With the above two traps in mind, we can calculate the exact size of Cell and then set the correct size of itemSize. Such as:


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

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

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

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

Code description:

The size of the current view is passed in, and the size of cell is dynamically calculated, which can be easily adapted to iPhone/iPad. The margins on both sides are hidden in a single column, and the gaps on both sides are displayed in multiple columns.

The above is the usage and description of IOS UICollectionView, hoping to help IOS development friends.


Related articles: