Display array data with image (Swift)

Hi everyone!

I'm making a food app where the user can save meals to categories, and add an image, ingredients, and the recipe.

The meal name is saved to a UserDefaults array. Then, a dictionary is created with the meal name, ingredients, recipe, and the image location path on the device - and saved.
For example:
Code Block
/*Save the new meal to the array*/
self.breakfasts.append(newMealName!)
/*Update UserDefaults with the new array*/
self.defaults.set(self.breakfasts, forKey: "breakfasts")
/*Define the dictionary*/
let dict = ["Name": newMealName, "Ingredients": newMealIngred, "Recipe": newMealRecipe, "Type": "breakfasts", "Image": imgPath]
/*Save the dictionary to UserDefaults*/
self.defaults.set(dict, forKey: newMealName!)

(I'm only using block comments for each comment here as the Developer Forums don't seem to support "//")

I need a way to display all of this on my app's home screen. Ideally, I'd like a side-scrolling collection view with the images that users upload, and the meal title displayed on them. (The last bit is easy enough, just a blur effect and a label)
If that's not possible, a TableView that shows all of the meals in a separate cell - and segues to a view with the meal name and associated info - would work for now.

I'm relatively new to Swift so I apologise if I'm doing anything wrong here — thanks so much to everyone in advance.

I look forward to your responses and I hope everyone is doing well during this time!

Replies

What is it you don't succeed in doing ?
  • create the collectionView in IB

  • define the dataSource for the collection, from defaults

  • load each collection cell through the cellForItemAt delegate func

I'm trying to work out how to display all the data. I have all of the data saved but no idea how to present it to the user. Thanks.
You have to do it in

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
   }

You would do something like:

define a class for the cell to conform to:

Code Block
class FirstCollectionViewCell: UICollectionViewCell {
@IBOutlet weak var imageCell: UIImageView!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
}

Code Block
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "FirstCollectionCell", for: indexPath) as! FirstCollectionViewCell
let imageView = UIImageView(image: UIImage(named: "the Image")) // GHere, gt the image from the userDefaults, not a fixed one
cell.contentView.insertSubview(imageView, at: 0)