1

我创建了一个简单的列表并想向其中添加用户。我的项目已激活 CoreDate,并且我已将以下代码添加到 SceneDelegate:

    let userStorage = UserStorage()
    let contentView = ContentView().environment(\.managedObjectContext, context).environmentObject(userStorage)

ContentView 的代码是这样的:

import SwiftUI

struct User: Identifiable {
    var id = UUID()
    var firstName = ""
    var lastName = ""
}

class UserStorage: ObservableObject {
    @Published var users = [User]()
}

struct ContentView: View {

    @State private var presentation = false
    @EnvironmentObject var userStorage: UserStorage

    var body: some View {

        VStack {
            Button(action: {
                self.presentation = true
            }) {
                Text("New User")
            }.sheet(isPresented: $presentation, onDismiss: {
                self.presentation = false
            }) {
                newuserView(presentation: self.$presentation, newUser: User())
            }
            List(userStorage.users) { singleUser in
                VStack {
                    Text(singleUser.firstName)
                    Text(singleUser.lastName)
                }
            }
        }
    }
}

struct newuserView : View {
    @Binding var presentation: Bool
    @State var newUser: User
    @EnvironmentObject var userStarage: UserStorage

    var body: some View {
        VStack {
            TextField("Put in first name please", text:$newUser.firstName)

            TextField("Put in last name please", text:$newUser.lastName)

            Button(action: {
                self.userStarage.users.append(self.newUser)
                self.presentation = false
            }) {
                Text("Add new User")
            }disabled(newUser.lastName.isEmpty || newUser.firstName.isEmpty)
        }.padding(.horizontal)
    }
}
struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

当我运行我的项目并想要添加用户时,我收到以下错误:

线程 1:致命错误:未找到 UserStorage 类型的 ObservableObject。UserStorage 的 View.environmentObject(_:) 作为该视图的祖先可能会丢失。

我曾尝试使用 .sheet 执行此操作,但它不起作用

4

1 回答 1

1

工作表创建不同的视图层次结构,因此.environmentObject默认情况下不会注入要在工作表中显示的视图 - 您必须手动进行

}.sheet(isPresented: $presentation, onDismiss: {
    self.presentation = false
}) {
    newuserView(presentation: self.$presentation, newUser: User())
        .environmentObject(self.userStorage)
}
于 2020-01-11T09:12:03.363 回答