// basic cell with centered label class QuickCell: UICollectionViewCell { let label = UILabel() override init(frame: CGRect) { super.init(frame: frame) commonInit() } required init?(coder: NSCoder) { super.init(coder: coder) commonInit() } func commonInit() { label.backgroundColor = UIColor(white: 0.95, alpha: 1.0) label.translatesAutoresizingMaskIntoConstraints = false contentView.addSubview(label) NSLayoutConstraint.activate([ label.centerXAnchor.constraint(equalTo: contentView.centerXAnchor), label.centerYAnchor.constraint(equalTo: contentView.centerYAnchor), ]) } } // tap anywhere outside the collection view to add 2-to-7 new items // tap any cell to reset to Zero items class QuickTestVC: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate { var photos: [Int] = [] var collectionView: UICollectionView! let colors: [UIColor] = [ .red, .green, .blue, .cyan, .yellow, .magenta, ] override func viewDidLoad() { super.viewDidLoad() let fl = UICollectionViewFlowLayout() fl.itemSize = .init(width: 80.0, height: 40.0) collectionView = UICollectionView(frame: .zero, collectionViewLayout: fl) collectionView.backgroundColor = .systemYellow collectionView.translatesAutoresizingMaskIntoConstraints = false view.addSubview(collectionView) let g = view.safeAreaLayoutGuide NSLayoutConstraint.activate([ collectionView.topAnchor.constraint(equalTo: g.topAnchor, constant: 20.0), collectionView.leadingAnchor.constraint(equalTo: g.leadingAnchor, constant: 20.0), collectionView.trailingAnchor.constraint(equalTo: g.trailingAnchor, constant: -20.0), collectionView.heightAnchor.constraint(equalToConstant: 300.0), ]) collectionView.register(QuickCell.self, forCellWithReuseIdentifier: "c") collectionView.dataSource = self collectionView.delegate = self } override func touchesBegan(_ touches: Set, with event: UIEvent?) { let startVal: Int = self.photos.count let newPhotos: [Int] = Array(startVal.. Int { print("numberOfItemsInSection:", self.photos.count) return self.photos.count } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let c = collectionView.dequeueReusableCell(withReuseIdentifier: "c", for: indexPath) as! QuickCell c.label.text = "\(self.photos[indexPath.item])" c.contentView.backgroundColor = colors[indexPath.item % colors.count] return c } func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { self.photos = [] collectionView.reloadData() } }