Skip to content

Instantly share code, notes, and snippets.

@wingchi
Created May 5, 2018 22:31
Show Gist options
  • Save wingchi/8c187283c2362dcddd218f1d62575acf to your computer and use it in GitHub Desktop.
Save wingchi/8c187283c2362dcddd218f1d62575acf to your computer and use it in GitHub Desktop.
Grid View Model with all item layout logic
import UIKit
class GridViewModel {
static var itemMargin: CGFloat = 8.0
var data: [Int] = (1...10).map { $0 }
func cellSize(for frame: CGRect, at indexPath: IndexPath) -> CGSize {
let height = (frame.height / 5) - 2 * GridViewModel.itemMargin
let fullWidth = frame.width
let halfWidth = (frame.width / 2) - (GridViewModel.itemMargin / 2)
let shouldBeFullWidth = cellShouldBeFullWidth(at: indexPath)
let width = shouldBeFullWidth ? fullWidth: halfWidth
return CGSize(width: width, height: height)
}
private func cellShouldBeFullWidth(at indexPath: IndexPath) -> Bool {
let count = data.count
guard indexPath.row < count else { return false }
switch indexPath.row {
case 0:
return count < 10
case 1:
return count < 9
case 2:
return count < 8 && count != 6
case 3, 4:
return count < 6
default:
return false
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment