Skip to content

Instantly share code, notes, and snippets.

@KrauserHuang
Created December 17, 2020 03:16
Show Gist options
  • Save KrauserHuang/ba01518156b11c49c3195aaf379f573c to your computer and use it in GitHub Desktop.
Save KrauserHuang/ba01518156b11c49c3195aaf379f573c to your computer and use it in GitHub Desktop.
override func viewDidLoad() {
super.viewDidLoad()
//cell and cell spacing
let itemSpace: CGFloat = 3
//how many colume in a row
let columeCount: CGFloat = 3
//將collectionViewLayout轉型成UICollectionViewFlowLayout(向下捲動)
let flowLayout = collectionViewLayout as? UICollectionViewFlowLayout
//計算cell寬度,利用畫面的寬減去要的間距然後再除以要拆分成幾格(這樣可以避開不同的型號的iphone算出對應的寬度
let width = floor((collectionView.bounds.width-itemSpace*(columeCount-1))/columeCount)
//設定cell的大小
flowLayout?.itemSize = CGSize(width: width, height: width)
//設成zero才會根據itemSize來設定cell大小,不然會被autoLayout條件影響(如果有額外設定cell autoLayout)
flowLayout?.estimatedItemSize = CGSize.zero
//定義cell間的間距(左右間距)
flowLayout?.minimumInteritemSpacing = itemSpace
//定義colume間的間距(上下間距)
flowLayout?.minimumLineSpacing = itemSpace
//定義cell到編框間的間距(上下左右)
// flowLayout?.sectionInset = UIEdgeInsets(top: 0, left: 5, bottom: 0, right: 5)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment