Created
November 2, 2016 19:23
-
-
Save BrandonShega/9aacbbdd8064fec9e8619e5a62ae3dc2 to your computer and use it in GitHub Desktop.
Collection View In Code
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//: Playground - noun: a place where people can play | |
import UIKit | |
import PlaygroundSupport | |
class MyViewController: UIViewController { | |
let collectionView: UICollectionView | |
let flowLayout: UICollectionViewFlowLayout | |
init() { | |
flowLayout = UICollectionViewFlowLayout() | |
collectionView = UICollectionView(frame: CGRect.zero, collectionViewLayout: flowLayout) | |
super.init(nibName: nil, bundle: nil) | |
setup() | |
} | |
override func viewDidLayoutSubviews() { | |
super.viewDidLayoutSubviews() | |
setupFlowLayout() | |
} | |
required init?(coder aDecoder: NSCoder) { | |
fatalError("init(coder:) has not been implemented") | |
} | |
private func setup() { | |
collectionView.delegate = self | |
collectionView.dataSource = self | |
view.backgroundColor = .white | |
view.addSubview(collectionView) | |
collectionView.backgroundColor = .white | |
collectionView.register(UICollectionViewCell.self, forCellWithReuseIdentifier: "Cell") | |
collectionView.collectionViewLayout = flowLayout | |
collectionView.translatesAutoresizingMaskIntoConstraints = false | |
collectionView.leftAnchor.constraint(equalTo: view.leftAnchor).isActive = true | |
collectionView.rightAnchor.constraint(equalTo: view.rightAnchor).isActive = true | |
collectionView.topAnchor.constraint(equalTo: view.topAnchor).isActive = true | |
collectionView.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true | |
} | |
private func setupFlowLayout() { | |
flowLayout.itemSize = CGSize(width: view.bounds.width - 40, height: 100) | |
flowLayout.minimumLineSpacing = 10 | |
flowLayout.minimumInteritemSpacing = 0 | |
} | |
} | |
extension MyViewController: UICollectionViewDelegate { | |
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { | |
print(indexPath) | |
} | |
} | |
extension MyViewController: UICollectionViewDataSource { | |
func numberOfSections(in collectionView: UICollectionView) -> Int { | |
return 1 | |
} | |
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { | |
return 10 | |
} | |
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { | |
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath) as UICollectionViewCell | |
cell.backgroundColor = .red | |
return cell | |
} | |
} | |
let vc = MyViewController() | |
PlaygroundPage.current.liveView = vc |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment