SwiftUI - 呈现工作表后导航栏按钮不可点击 [英] SwiftUI - Navigation bar button not clickable after sheet has been presented

查看:40
本文介绍了SwiftUI - 呈现工作表后导航栏按钮不可点击的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

几周前我刚刚开始使用 SwiftUI,我正在学习.今天我遇到了一个问题.

I have just started using SwiftUI a couple of weeks ago and i'm learning. Today I ran into a into an issue.

当我展示带有导航栏项目按钮的工作表然后关闭 ModalView 并返回到 ContentView 时,我发现自己无法再次单击导航栏项目按钮.

When I present a sheet with a navigationBarItems-button and then dismiss the ModalView and return to the ContentView I find myself unable to click on the navigationBarItems-button again.

我的代码如下:

struct ContentView: View {

    @State var showSheet = false

    var body: some View {
        NavigationView {
            VStack {
                Text("Test")
            }.sheet(isPresented: self.$showSheet) {
                ModalView()
            }.navigationBarItems(trailing:
                Button(action: {
                    self.showSheet = true
                }) {
                    Text("SecondView")
                }
            )
        }
    }
}

struct ModalView: View {

    @Environment(\.presentationMode) var presentation

    var body: some View {
        VStack {
            Button(action: {
                self.presentation.wrappedValue.dismiss()
            }) {
                Text("Dismiss")
            }
        }
    }
}

推荐答案

我认为这是因为 presentationMode 不是从演示者视图继承的,所以演示者不知道模态是已经关闭.您可以通过将 presentationMode 添加到 Presenter(在本例中添加到 ContentView)来解决此问题.

I think this happens because the presentationMode is not inherited from the presenter view, so the presenter didn't know that the modal is already closed. You can fix this by adding presentationMode to presenter, in this case to ContentView.

struct ContentView: View {

    @Environment(\.presentationMode) var presentation
    @State var showSheet = false

    var body: some View {
        NavigationView {
            VStack {
                Text("Test")
            }.sheet(isPresented: self.$showSheet) {
                ModalView()
            }.navigationBarItems(trailing:
                Button(action: {
                    self.showSheet = true
                }) {
                    Text("SecondView")
                }
            )
        }
    }
}

在 Xcode 12.5 上测试.

Tested on Xcode 12.5.

这是完整的工作示例.

这篇关于SwiftUI - 呈现工作表后导航栏按钮不可点击的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆