Skip to content

Instantly share code, notes, and snippets.

@bdewey
Created March 5, 2023 01:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bdewey/55ced9d536c80fb8837c4f2bfab15392 to your computer and use it in GitHub Desktop.
Save bdewey/55ced9d536c80fb8837c4f2bfab15392 to your computer and use it in GitHub Desktop.
//: A UIKit based Playground for presenting user interface
import UIKit
import PlaygroundSupport
private let reuseIdentifier = "reuse"
/// A playground for trying different UICOllectionViewCompositionalLayout techniques.
class MyViewController : UIViewController, UICollectionViewDataSource {
private let data: [[UIColor]] = [
[.red, .orange, .yellow, .green],
[.blue, .black]
]
/// A layout of independent lines. Each line scrolls horizontally.
private let horizontalScrollingLinesLayout: UICollectionViewCompositionalLayout = {
let item = NSCollectionLayoutItem(
layoutSize: NSCollectionLayoutSize(
widthDimension: .fractionalWidth(1),
heightDimension: .fractionalHeight(1)
)
)
let group = NSCollectionLayoutGroup.horizontal(
layoutSize: NSCollectionLayoutSize(widthDimension: .absolute(100), heightDimension: .absolute(100)),
subitems: [item]
)
let section = NSCollectionLayoutSection(group: group)
section.orthogonalScrollingBehavior = .continuous
section.interGroupSpacing = 10
section.contentInsets = NSDirectionalEdgeInsets(top: 10, leading: 10, bottom: 0, trailing: 10)
return UICollectionViewCompositionalLayout(section: section)
}()
private lazy var collectionView: UICollectionView = {
let view = UICollectionView(frame: .zero, collectionViewLayout: horizontalScrollingLinesLayout)
view.register(UICollectionViewCell.self, forCellWithReuseIdentifier: reuseIdentifier)
view.dataSource = self
// DON'T DO THIS
// view.contentInset = UIEdgeInsets(top: 10, left: 10, bottom: 10, right: 10)
return view
}()
func numberOfSections(in collectionView: UICollectionView) -> Int {
data.count
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
data[section].count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath)
cell.backgroundColor = data[indexPath.section][indexPath.row]
return cell
}
override func loadView() {
view = collectionView
}
}
// Present the view controller in the Live View window
PlaygroundPage.current.liveView = MyViewController()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment