DEV Community

Avelyn Hyunjeong Choi
Avelyn Hyunjeong Choi

Posted on • Edited on

UICollectionView in Xcode

1.Add a collection view in the View Controller
1

2.Set a layout of the collection view
2

3.Add a constraint to the collection view
3

4.Add another required objects inside of collection view and add required constraints
4

4-1

*NOTE: you can decide how many line will be displayed by specifying the line number
lable-note

5.Create a collection view cell, RecipeCVCell
5

import UIKit

class RecipeCVCell: UICollectionViewCell {
    @IBOutlet weak var imageView: UIImageView!
    @IBOutlet weak var nameLabel: UILabel!
    @IBOutlet weak var descriptionLabel: UILabel!
}
Enter fullscreen mode Exit fullscreen mode

6.Select Collection View Cell and add RecipeCVCell in a custom class
6

7.Select RecipeCVCell and add an identifier, RecipeCell
7

8.Connect Collection View with your view controller

    override func viewDidLoad() {
        super.viewDidLoad()
        collectionView.dataSource = self
    }
Enter fullscreen mode Exit fullscreen mode

9.Create an extension of UICollectionViewDataSource

  • cellForItemAt will be implemented for the collection view
extension ViewController: UICollectionViewDataSource {
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return recipes.count
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "RecipeCell", for: indexPath) as! RecipeCVCell
        let recipe = recipes[indexPath.item]

        cell.nameLabel.text = recipe.name
        cell.descriptionLabel.text = recipe.description
        cell.imageView.image = UIImage(systemName: recipe.image)

        return cell
    }
}
Enter fullscreen mode Exit fullscreen mode

10.Demo
10

Top comments (0)