我有以下视图 ModalView
由父视图 ParentView
使用工具栏中的按钮打开
** 父视图 **
import SwiftUI
struct ParentView: View {
@EnvironmentObject var environmentObject: MainStore
@State private var showCreationView = false
var body: some View {
NavigationView {
Text("ENV_OBJ Count: \(environmentObject.shoppingChartFullList.count)")
.navigationBarTitle(Text("Navigation Bar Title"))
.toolbar {
ToolbarItem(placement: .bottomBar) {
Button(action: { showCreationView = true }) {
Image(systemName: "plus")
}
.sheet(isPresented: $showCreationView, content: {
ModalView(showModelView: $showCreationView)
})
}
}
}
}
}
struct ParentView_Previews: PreviewProvider {
static var previews: some View {
ParentView().environmentObject(MainStore())
}
}
** 模态视图 **
import SwiftUI
struct ModalView: View {
@EnvironmentObject var environmentObject: MainStore
@Binding var showModelView: Bool
@State var newItem = ShoppingChartModel()
var body: some View {
Text(/*@START_MENU_TOKEN@*/"Hello, World!"/*@END_MENU_TOKEN@*/)
Button(action: {
environmentObject.shoppingChartFullList.append(newItem)
self.showModelView = false
}) {Text("Salva")}
}
}
struct ModalView_Previews: PreviewProvider {
static var previews: some View {
ModalView(showModelView: .constant(true)).environmentObject(MainStore())
}
}
** 总店 **
import Foundation
import SwiftUI
import Combine
final class MainStore: ObservableObject {
//An observable object needs to publish any changes to its data, so that its subscribers can pick up the change.
@Published var shoppingChartFullList: [ShoppingChartModel] = load()
}
问题在于,由模态视图中的保存按钮执行的操作不会关闭模态(即使它正确更新了布尔变量和 Env_Obj)。
似乎和工具栏有关...其实如果我把导航视图和工具栏去掉,把按钮直接放在一个堆栈里...就可以了...
在 Parent2View 中,我删除了 NavigationView 并在 Text 属性之后直接在视图中配置了按钮。它按预期工作。
import SwiftUI
struct ParentView2: View {
@EnvironmentObject var environmentObject: MainStore
@State private var showCreationView = false
var body: some View {
VStack {
Text("ENV_OBJ Count: \(environmentObject.shoppingChartFullList.count)")
Button(action: { showCreationView = true }) {
Image(systemName: "plus")
}
.sheet(isPresented: $showCreationView, content: {
ModalView(showModelView: $showCreationView)
})
}
}
}
struct ParentView2_Previews: PreviewProvider {
static var previews: some View {
ParentView2().environmentObject(MainStore())
}
}
更新 好的,我终于找到了解决方案。问题是工具栏。如果 ParentView 修改如下,一切都开始正常运行
struct ParentView: View {
@EnvironmentObject var environmentObject: MainStore
@State private var showCreationView = false
var body: some View {
NavigationView {
Text("ENV_OBJ Count: \(environmentObject.shoppingChartFullList.count)")
.navigationBarTitle("Nav View Title")
.navigationBarItems(trailing:
Button(action: {
self.showCreationView.toggle()
})
{
Image(systemName: "plus")
.font(Font.system(.title))
}
)
}
.sheet(isPresented: $showCreationView) {
ModalView(showModelView: $showCreationView)
}
}
}
谢谢! 克里斯蒂安