Hi Guys,
I’ll use Chris’ Recipe List App as an example as his code is neater than mine!
I would like to bind the ‘selectedServingSize’ var to the ‘servings’ var in the model, so that the picker starts on the suggested serving size and in my case allows the picker to update the original
‘servings’ var so that the updated number is used in other calculations on the app.
View Code;
struct RecipeDetailView: View {
var recipe:Recipe **@State var selectedServingSize = 2** var body: some View { ScrollView { VStack (alignment: .leading) { // MARK: Recipe Image Image(recipe.image) .resizable() .scaledToFill() // MARK: Recipe title Text(recipe.name) .bold() .padding(.top, 20) .padding(.leading) .font(Font.custom("Avenir Heavy", size: 24)) // MARK: Serving size picker VStack (alignment: .leading) { Text("Select your serving size:") .font(Font.custom("Avenir", size: 15)) Picker("", selection: $selectedServingSize) { Text("2").tag(2) Text("4").tag(4) Text("6").tag(6) Text("8").tag(8) } .font(Font.custom("Avenir", size: 15)) .pickerStyle(SegmentedPickerStyle()) .frame(width:160) } .padding() // MARK: Ingredients VStack(alignment: .leading) { Text("Ingredients") .font(Font.custom("Avenir Heavy", size: 16)) .padding([.bottom, .top], 5) ForEach (recipe.ingredients) { item in Text("• " + RecipeModel.getPortion(ingredient: item, recipeServings: recipe.servings, targetServings: selectedServingSize) + " " + item.name.lowercased()) .font(Font.custom("Avenir", size: 15)) } } .padding(.horizontal) // MARK: Divider Divider() // MARK: Directions VStack(alignment: .leading) { Text("Directions") .font(Font.custom("Avenir Heavy", size: 16)) .padding([.bottom, .top], 5) ForEach(0..<recipe.directions.count, id: \.self) { index in Text(String(index+1) + ". " + recipe.directions[index]) .padding(.bottom, 5) .font(Font.custom("Avenir", size: 15)) } } .padding(.horizontal) } } }
}
Model Code:
class Recipe: Identifiable, Decodable {
var id:UUID?
var name:String
var featured:Bool
var image:String
var description:String
var prepTime:String
var cookTime:String
var totalTime:String
var servings:Int
var highlights:[String]
var ingredients:[Ingredient]
var directions:[String]
}
class Ingredient: Identifiable, Decodable {
var id:UUID?
var name:String
var num:Int?
var denom:Int?
var unit:String?
}