[Swift] iOS UICollectionView: Cell size calculation trap, uicollectionviewcell
Preface
Problems caused by unfamiliar APIs may occur if you take it for granted. Here we record the use of UICollectionView.
Statement
You are welcome to repost, but please keep the original source of the article :)
Blog: http://www.cnblogs.com
Farmer's uncle: http://over140.cnblogs.com
Body
Trap 1: minimumLineSpacing and minimumInteritemSpacing
It is easy to set these two attributes to 0. These two attributes are the minimum row spacing and the minimum column spacing. Note that they are the minimum !! That is to say, it can actually be greater than 0, not the spacing is 0
Trap 2: sectionInset
Set cell margins. At first, I thought it was the margin of every cell, and the adjacent cells would overlay the result. In fact, this is not the case. This attribute only ensures the spacing between adjacent cells and does not overlay them !!
After understanding the above two traps, we can accurately calculate the Cell size, and then set 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 { 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:
Input the size of the current view to dynamically calculate the cell size, which can be easily adapted to the iPhone/iPad. When a single column is used, the margins on both sides are hidden. When multiple columns are used, the gap between the two sides is displayed.