1.Add a collection view in the View Controller
2.Set a layout of the collection view
3.Add a constraint to the collection view
4.Add another required objects inside of collection view and add required constraints
*NOTE: you can decide how many line will be displayed by specifying the line number
5.Create a collection view cell, RecipeCVCell
import UIKit
class RecipeCVCell: UICollectionViewCell {
@IBOutlet weak var imageView: UIImageView!
@IBOutlet weak var nameLabel: UILabel!
@IBOutlet weak var descriptionLabel: UILabel!
}
6.Select Collection View Cell
and add RecipeCVCell
in a custom class
7.Select RecipeCVCell
and add an identifier, RecipeCell
8.Connect Collection View with your view controller
override func viewDidLoad() {
super.viewDidLoad()
collectionView.dataSource = self
}
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
}
}
Top comments (0)