import SwiftUI
struct AddRecipeView: View {
@EnvironmentObject var recipesVM: RecepiesViewModel
@State private var name = ""
@State private var selectedCategory = Category.main
@State private var description = ""
@State private var ingredients = ""
@State private var directions = ""
@State private var navigateTorecipe = false
@Environment(\.dismiss) var dismiss
var body: some View {
NavigationView {
Form {
Section(header: Text("Name")) {
TextField("Recipe Name", text: $name)
}
Section(header: Text("Category")) {
Picker("Category", selection: $selectedCategory) {
ForEach(Category.allCases) { category in
Text(category.rawValue)
.tag(category)
}
}
.pickerStyle(.menu)
}
Section(header: Text("Description")) {
TextEditor(text: $description)
}
Section(header: Text("Ingredients")) {
TextEditor(text: $ingredients)
}
Section(header: Text("Directions")) {
TextEditor(text: $directions)
}
}
.toolbar(content: {
ToolbarItem(placement: .navigationBarLeading) {
Button {
dismiss()
} label: {
Label("Cancel", systemImage: "xmark")
}
}
ToolbarItem {
NavigationLink(isActive: $navigateTorecipe) {
RecipeView(recipe: recipesVM.recipes.sorted{ $0.datePublished > $1.datePublished }[0])
.navigationBarBackButtonHidden(true)
} label: {
Button {
saveRecipe()
navigateTorecipe = true
} label: {
Label("Done", systemImage: "checkmark")
.labelStyle(.iconOnly )
}
}
.disabled(name.isEmpty)
}
})
.navigationTitle("New Recipe")
.navigationBarTitleDisplayMode(.inline)
}
.navigationViewStyle(.stack)
}
}
struct AddRecipeView_Previews: PreviewProvider {
static var previews: some View {
AddRecipeView()
.environmentObject(RecepiesViewModel())
}
}
extension AddRecipeView {
private func saveRecipe() {
let now = Date()
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-mm-dd"
let datePublished = dateFormatter.string(from: now)
print(datePublished)
let recipe = Recipe(name: name, image: "", description: description, ingredients: ingredients, directions: directions, category: selectedCategory.rawValue, datePublished: datePublished, url: "")
recipesVM.addRecipe(recipe: recipe)
}
}
New Recipe.swift
import SwiftUI
struct NewRecipeView: View {
@State private var showAddRecipe = false
var body: some View {
NavigationView {
Button("Add recipe mannually", action: {
showAddRecipe = true
})
.navigationTitle("New Recipe")
}
.navigationViewStyle(.stack)
.sheet(isPresented: $showAddRecipe) {
AddRecipeView()
}
}
}
struct NewRecipeView_Previews: PreviewProvider {
static var previews: some View {
NewRecipeView()
}
}
Then appears another recipe instead of recipe that i have add recently
Why when I add new recipe pops up the latest recipe, but in my recipes the new recipe appears? It supposed to pop up the recipe that I have added
May be NavigationLink or sth?
How can I remove this error?