Skip to content

Instantly share code, notes, and snippets.

@fedejordan
Last active February 26, 2018 15:10
Show Gist options
  • Save fedejordan/584acb600bc660a2cf220a79c4c7754d to your computer and use it in GitHub Desktop.
Save fedejordan/584acb600bc660a2cf220a79c4c7754d to your computer and use it in GitHub Desktop.
Blog02 - ItemsViewController with UICollectionView
import UIKit
class ItemsViewController: UIViewController {
@IBOutlet private weak var itemsCollectionView: UICollectionView!
private var itemsInteractor = ItemsInteractor()
override func viewDidLoad() {
super.viewDidLoad()
itemsInteractor.loadData()
itemsCollectionView.register(UINib.init(nibName: ItemCollectionViewCell.identifier, bundle: nil), forCellWithReuseIdentifier: ItemCollectionViewCell.identifier)
}
}
// MARK:- UICollectionViewDataSource
extension ItemsViewController: UICollectionViewDataSource {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return itemsInteractor.itemsCount()
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: ItemCollectionViewCell.identifier, for: indexPath) as? ItemCollectionViewCell else { return UICollectionViewCell() }
let itemImage = itemsInteractor.itemImage(atIndex: indexPath.item)
let itemName = itemsInteractor.itemName(atIndex: indexPath.item)
cell.setup(withItemImage: itemImage, itemName: itemName)
return cell
}
}
// MARK:- UICollectionViewDelegateFlowLayout
extension ItemsViewController: UICollectionViewDelegateFlowLayout {
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
let cellSize = CGSize(width: ItemCollectionViewCell.width, height: ItemCollectionViewCell.height)
return cellSize
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
itemsInteractor.didSelectItem(atIndex: indexPath.item)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment