Skip to content

Instantly share code, notes, and snippets.

@richimf
Created March 24, 2020 15:14
Show Gist options
  • Save richimf/9a9c96d88b9b0d9b6b8d0e1db9639f28 to your computer and use it in GitHub Desktop.
Save richimf/9a9c96d88b9b0d9b6b8d0e1db9639f28 to your computer and use it in GitHub Desktop.
CollectionView Custom Layout
import UIKit
enum CollectionDisplay {
case list
case twoColumns
}
class HomeCustomLayout: c {
var cellHeight: CGFloat = 100
var display: CollectionDisplay = .twoColumns {
didSet {
if display != oldValue {
self.invalidateLayout()
}
}
}
convenience init(display: CollectionDisplay) {
self.init()
self.display = display
self.minimumLineSpacing = 10
self.minimumInteritemSpacing = 10
self.configLayout()
}
func configLayout() {
switch display {
case .twoColumns:
self.itemSize = getGridSize()
case .list:
self.itemSize = getListSize()
}
}
func getGridSize() -> CGSize {
guard let collectionView = self.collectionView else { return .zero }
let squareWidth = (collectionView.frame.width - minimumInteritemSpacing) / 2
return CGSize(width: squareWidth , height: squareWidth)
}
func getListSize() -> CGSize {
guard let collectionView = self.collectionView else { return .zero }
return CGSize(width: collectionView.frame.width , height: cellHeight)
}
override func invalidateLayout() {
super.invalidateLayout()
self.configLayout()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment