Skip to content

Instantly share code, notes, and snippets.

@laevandus
Created January 19, 2019 14:36
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 laevandus/4c7a4eb2cdb01d27b487cf440161d735 to your computer and use it in GitHub Desktop.
Save laevandus/4c7a4eb2cdb01d27b487cf440161d735 to your computer and use it in GitHub Desktop.
final class CollectionViewController: UICollectionViewController {
// MARK: Managing the View
enum ReuseIdentifier: String {
case item = "ItemCell"
}
override func viewDidLoad() {
super.viewDidLoad()
collectionView!.register(CircleCollectionViewCell.self, forCellWithReuseIdentifier: ReuseIdentifier.item.rawValue)
navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .add, target: self, action: #selector(addItem))
}
// MARK: Managing the Content
private var items: [UIColor] = [.random(), .random(), .random()]
@objc private func addItem() {
items.append(.random())
collectionView.insertItems(at: [IndexPath(item: items.count - 1, section: 0)])
}
// MARK: Collection View Data Source
override func numberOfSections(in collectionView: UICollectionView) -> Int {
return items.count > 0 ? 1 : 0
}
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return items.count
}
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: ReuseIdentifier.item.rawValue, for: indexPath) as! CircleCollectionViewCell
cell.backgroundView?.backgroundColor = items[indexPath.item]
cell.titleLabel.text = "\(indexPath.item)"
return cell
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment