How to implement simple Collection View using storyboard in Swift5
[Step 1] : Add collectionView in your storyboard (Main.storyboard) or custom storyboard.
[Step 2] : Declare and link your collectionView in class ViewController
or your custom class.
@IBOutlet weak var collectionView: UICollectionView!
private let cellId = "cellId"
[Step 3] : Add inherit UICollectionViewDataSource & (using extension)
extension ViewController: UICollectionViewDataSource {func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {return 5}func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellId, for: indexPath)
cell.backgroundColor = .redreturn cell}}
[Step 4] : Add inherit UICollectionViewDelegate
extension ViewController: UICollectionViewDelegate {func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {print(indexPath.item)}}
[Step 5] : Declare delegate, datasource = self & register collectionViewCell in class ViewController
override func viewDidLoad() {
super.viewDidLoad()collectionView.delegate = self
collectionView.dataSource = selfcollectionView.register(UICollectionViewCell.self, forCellWithReuseIdentifier: cellId)}
[Step 6] : Add inherit UICollectionViewDelegateFlowLayout for adjusting size of cell.
extension ViewController: UICollectionViewDelegateFlowLayout {func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {return CGSize(width: view.frame.width, height: 200)}}
Result: