我创建了一个简单的列表,并希望向其中添加用户。我的项目已激活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进行此操作,但这不起作用
答案 0 :(得分:0)
Sheet创建了不同的视图层次结构,因此默认情况下.environmentObject
不会注入视图中以显示在表单中-您必须手动进行
}.sheet(isPresented: $presentation, onDismiss: {
self.presentation = false
}) {
newuserView(presentation: self.$presentation, newUser: User())
.environmentObject(self.userStorage)
}