Skip to content

Instantly share code, notes, and snippets.

View froggomad's full-sized avatar

Kenny Dubroff (froggomad) froggomad

View GitHub Profile
extension TitledCollectionViewController: UICollectionViewDelegate {
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
print("tapped cell at \(indexPath)")
}
}
extension TitledCollectionViewController: TitledCollectionViewDelegate {
func itemWasSelected(_ fruit: Fruit) {
print("Fruit named \(fruit.description) was selected")
}
func itemWasSelected(_ vegetable: Vegetable) {
print("Vegetable named \(vegetable.description) was selected")
}
extension TitledCollectionView: UICollectionViewDelegate {
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
updateControllerDelegate(with: indexPath.item)
}
private func updateControllerDelegate(with item: Int) {
switch self.produce {
case .fruit:
let fruit = Fruit.allCases[item]
delegate?.itemWasSelected(fruit)
protocol TitledCollectionViewDelegate: AnyObject {
func itemWasSelected(_ fruit: Fruit)
func itemWasSelected(_ vegetable: Vegetable)
}
class TitledCollectionViewController: UIViewController {
lazy var fruitView = TitledCollectionView(produce: .fruit)
lazy var vegetableView = TitledCollectionView(produce: .vegetable)
override func viewDidLoad() {
super.viewDidLoad()
setupViews()
}
func setupViews() {
extension TitledCollectionView {
class Layout: UICollectionViewFlowLayout {
static let heightConstant: CGFloat = 150
override func prepare() {
super.prepare()
guard let collectionView = collectionView else { return }
// TODO: why -13 to make the size even? section insets?
itemSize = CGSize(width: collectionView.frame.width / 3 - 13, height: Self.heightConstant - 40)
extension TitledCollectionView: UICollectionViewDataSource {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
produce?.count ?? 0
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: ProduceCollectionViewCell.identifier, for: indexPath) as! ProduceCollectionViewCell
import UIKit
class TitledCollectionView: UIView {
var produce: Produce? {
didSet {
titleLabel.text = produce?.description
}
}
class ProduceCollectionViewCell: UICollectionViewCell {
static let identifier = "ProduceCollectionViewCell"
var viewModel: ProduceViewModel? {
didSet {
titleLabel.text = viewModel?.description
}
}
lazy var titleLabel: UILabel = {
enum Fruit: String {
case apple
case orange
case dragonFruit
var description: String {
var name: String = ""
for char in String(describing: rawValue) {
let strChar = String(char)