SwiftUI弹窗关闭异常问题求助:点击添加按钮后无法关闭AddView
SwiftUI弹窗关闭异常问题求助:点击添加按钮后无法关闭AddView
嘿,我仔细看了你的代码,发现几个很可能导致这个问题的点,咱们一步步来解决:
问题1:AddView的Body结构违规
你的AddView的body里直接并列了两个VStack和一个Button,但SwiftUI要求body必须返回单个View。这种多View直接并列的写法会导致布局混乱,甚至可能让按钮的交互区域失效——这大概率就是点击添加按钮后,关闭按钮失灵的核心原因。
问题2:过时的弹窗关闭方式
你现在用的presentationMode.wrappedValue.dismiss()是iOS 15之前的旧写法,现在更推荐用@Environment(\.dismiss)提供的dismiss()方法,不仅更简洁,交互可靠性也更高。
修复后的AddView代码
我把你的AddView做了针对性调整,主要修改了这些地方:
- 用一个外层
VStack包裹所有内容,保证body符合单View返回要求 - 替换成
dismiss()方法关闭弹窗 - 优化了布局间距,让界面更规整
struct AddView: View { @ObservedObject var destinationModel: DestinationModel @Environment(\.modelContext) var context @Environment(\.dismiss) var dismiss // 替代旧的presentationMode var body: some View { // 外层VStack包裹所有元素,确保body返回单个View VStack(spacing: 20) { // 顶部的Fertig按钮区域 HStack { Button("Fertig") { dismiss() // 直接调用dismiss关闭弹窗 } .padding(.top, 20) .padding(.leading, 20) .font(.title3) Spacer() } // 输入框组 VStack(alignment: .center, spacing: 15) { TextField("Name", text: $destinationModel.names) .padding(.leading, 20) .frame(width: 280, height: 40) .background(Color.gray) .foregroundStyle(Color.black) .font(.title2) .clipShape(RoundedRectangle(cornerSize: CGSize(width: 20, height: 10))) TextField("Shop", text: $destinationModel.shops) .padding(.leading, 20) .frame(width: 280, height: 40) .background(Color.gray) .foregroundStyle(Color.black) .font(.title2) .clipShape(RoundedRectangle(cornerSize: CGSize(width: 20, height: 10))) TextField("Preis", text: $destinationModel.prices) .padding(.leading, 20) .frame(width: 280, height: 40) .background(Color.gray) .foregroundStyle(Color.black) .font(.title2) .clipShape(RoundedRectangle(cornerSize: CGSize(width: 20, height: 10))) TextField("Vergünstigung", text: $destinationModel.cuts) .padding(.leading, 20) .frame(width: 280, height: 40) .background(Color.gray) .foregroundStyle(Color.black) .font(.title2) .clipShape(RoundedRectangle(cornerSize: CGSize(width: 20, height: 10))) } Spacer() // Hinzufügen按钮 Button("Hinzufügen") { let kauf = Destination(name: destinationModel.names, shop: destinationModel.shops, cut: destinationModel.cuts, price: destinationModel.prices) context.insert(kauf) // 清空输入框内容 destinationModel.cuts = "" destinationModel.shops = "" destinationModel.prices = "" destinationModel.names = "" } .padding() .background(Color.blue) .foregroundStyle(Color.white) .clipShape(RoundedRectangle(cornerRadius: 10)) } .background(Color(red: 242/255, green: 242/255, blue: 247/255)) .ignoresSafeArea() } }
额外优化建议
另外,在你的ContentView里,sheet附加到Button上的写法虽然能运行,但更规范的做法是把sheet直接绑定到父View(比如NavigationStack),逻辑会更清晰:
// 在ContentView的body中调整sheet位置 NavigationStack { // ... 原有的ZStack、VStack、List等内容 ... } .sheet(isPresented: $destinationModel.showingAddView) { AddView(destinationModel: destinationModel) }
先试试修复AddView的结构问题,这应该就能解决弹窗无法关闭的问题啦!
备注:内容来源于stack exchange,提问作者Jamie_Gerber
相关产品推荐
相关产品推荐

