SwiftUI中Menu组件内按钮点击触发sheet无法弹出问题求解
问题根因
- Sheet的
isPresented绑定和对应的modifier放在了Menu内部的子视图TestButtonInMenu中 - Menu属于临时弹出的容器,点击内部选项后Menu会自动关闭,内部的子视图会被立即销毁,状态
showingSheet变更后对应的sheet也没有挂载的视图层级可以渲染,自然无法弹出。
解决方法
将sheet的状态和modifier提升到上层稳定的视图(比如你的ContentView)中,Menu内部的按钮只负责修改这个全局状态即可,代码示例如下:
import SwiftUI struct SheetView: View { @Environment(\.presentationMode) var presentationMode var body: some View { Button("Press to dismiss") { presentationMode.wrappedValue.dismiss() } .font(.title) .padding() .background(Color.black) } } enum SampleEnum: String, CaseIterable { case one, two, three, four } struct ContentView: View { // 将sheet状态提升到上层稳定视图 @State private var showingSheet = false var body: some View { Form { Section { VStack { ForEach(SampleEnum.allCases, id:\.self) { id in Menu("\(Text(id.rawValue))") { // Menu内部按钮只负责修改状态 Button("Show Sheet") { showingSheet.toggle() } } } } } } // sheet挂载到稳定的ContentView层级上 .sheet(isPresented: $showingSheet) { SheetView() } } }
如果需要根据点击的不同Menu选项传递参数给sheet,可以将showingSheet替换为@State的可选值类型,配合sheet(item:)的初始化方法使用即可,该需求在SwiftUI中完全可以实现。
内容的提问来源于stack exchange,提问作者Phantom59
相关产品推荐
相关产品推荐

