简体   繁体   中英

UICollectionView: Displaying different cells that reference each other, Swift 3.0

Requirement:

I am currently working on a fun Recipe application that is utilizing a UICollectionView to function in the same way as a UITableView , ie, as simply just a list.

When the screen loads, the user will see cells pertaining to a particular "Recipe". Each cell has a label to display the Recipe name, and an "add ingredient" button.

Ex

  • Recipe: "Chicken Parmesan" [Add Ingredient]
  • Recipe: "Vegetable Omelette" [Add Ingredient]
  • Recipe: "Shrimp Fried Rice" [Add Ingredient]

When an "ingredient" is added, I would like a separate cell, that simply contains a UILabel , to be displayed under the Recipe cell that it pertains to, with the new ingredient. Ex//

  • Recipe: "Chicken Parmesan" [Add Ingredient]
  • Ingredient: "8oz Chicken Breast
  • Recipe: "Vegetable Omelette" [Add Ingredient]
  • Recipe: "Shrimp Fried Rice" [Add Ingredient]

Issue:

I'm having quite a hard time thinking up the logic to implement this in cellForItemAt indexPath , nor am I sure if logic there alone is enough to solve this problem. I have created custom cells for both the "Recipe" and "Ingredient" already, and would like input on how the control flow should be implemented, if not the correct structure of UIKit objects, to make this perform correctly.

Thank you for your input.

Keep a list of the items you want to display (eg in an Array). In the DataSource methods you always refer to that list. So when asked for number of items you return the count of that list, when populating cells in cellForIndexPath, you get the cells title from that list.

Now when you want to add a cell, add an item to your list first. Then call insertItems(at:) on the CollectionView. That will trigger a call to cellForIndexPath where you have to prepare the new cell when its indexPath is called. You just have to keep track of the type of cell each item should display (eg by using a dictionary with "type" and "title" as the item in your list).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM