Базовый объект данных все еще сохраняется при отклонении / отмене в presentationMode SwiftUI - PullRequest
1 голос
/ 17 января 2020

Когда я пытаюсь отклонить / отменить модальный объект Add, он создает пустой объект вместо просто отмены.

Я пробовал deleteObject, context.rollback () и кучу другие случайные вещи. Хотелось бы получить некоторую помощь и ответить на любые вопросы.

Я понимаю, что это не проблема, поместив кнопку «Отмена» в NavigationBarItem, но хотел бы понять, как сделать отдельную «отмену ( или отклонить) ".

ContentView.swift

import SwiftUI
import CoreData


struct ContentView: View {
    @Environment(\.managedObjectContext) var moc
    @FetchRequest(entity: Game.entity(), sortDescriptors: [NSSortDescriptor(keyPath: \Game.gameName, ascending: true)]) var games: FetchedResults<Game>
    @State private var showingAddGame = false


    var body: some View {
        GeometryReader { geometry in
            NavigationView {
                List {
                    ForEach(self.games, id: \.self) { games in
                        NavigationLink(destination: GameGoalsDetail(game: games)) {
                            VStack(alignment: .leading) {
                                Text(games.gameName ?? "Unknown Game")
                                Text(games.gameDescription ?? "Unknown Game Description")
                            }
                        }
                    }
                    .onDelete(perform: self.removeGames)
                    }

                .navigationBarItems(leading:
                    HStack {
                        Button(action: {
                                self.showingAddGame.toggle()
                            }) {
                                Text("Add Game")
                                    .padding(.top, 50)
                                    .foregroundColor(Color.yellow)
                        }.sheet(isPresented: self.$showingAddGame) {
                                AddGameView().environment(\.managedObjectContext, self.moc)
                        }
                        Image("Game Goals App Logo")
                        .resizable()
                        .frame(width: 100, height: 100)
                        .padding(.leading, (geometry.size.width / 2.0) + -160)
                        .padding(.bottom, -50)
                    }, trailing:
                        EditButton()
                            .padding(.top, 50)
                            .foregroundColor(Color.yellow)
                            )
            }
        }
    }

    func removeGames(at offsets: IndexSet) {
        for index in offsets {
            let game = games[index]
            moc.delete(game)
        }
        try? moc.save()
    }
}


struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
        let newGame = Game(context: context)
        newGame.gameName = "Apex Legends"
        newGame.gameDescription = "Maybe this will work"
        return ContentView().environment(\.managedObjectContext, context)
    }
}

AddGameView.swift

import SwiftUI
import CoreData


struct AddGameView: View {

    @Environment(\.managedObjectContext) var moc
    @FetchRequest(entity: Game.entity(), sortDescriptors: []) var games: FetchedResults<Game>
    @Environment(\.presentationMode) var presentationMode

    @State private var gameName = ""
    @State private var gameDescription = ""
    @State private var showingAlert = false

    var body: some View {
        Form {
            Section {
                TextField("Game Name", text: $gameName)
                TextField("Game Description", text: $gameDescription)
            }
            HStack {
                Button("Add Game") {
                    let newGame = Game(context: self.moc)
                    newGame.gameName = self.gameName
                    newGame.gameDescription = self.gameDescription

                    do {
                        try self.moc.save()
                        self.presentationMode.wrappedValue.dismiss()
                    } catch {
                        print("Whoops! \(error.localizedDescription)")
                    }

                }
                Button(action: {
                    self.presentationMode.wrappedValue.dismiss()
                }) {
                    Text("Cancel")
                }
                .padding(10)
                .foregroundColor(Color.white)
                .background(Color.red)
            }
        }
    }
}

struct AddGameView_Previews: PreviewProvider {
    static var previews: some View {
        AddGameView()
    }
}

Я искал по всему, так что если есть что-то, что Я пропустил пост стека, пожалуйста, свяжите его, так как я хотел бы не только исправить это, но и понять, почему.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...