SwiftUI如何通过TabView以模态视图的形式呈现视图?

4

我有一个如下所示的 TabView

struct ContentView: View {
    @State private var selection = 0
    @State var newListingPresented = false

    var body: some View {
        TabView(selection: $selection){

            // Browse
            BrowseView()
                .tabItem {
                    VStack {
                        Image(systemName: (selection == 0 ? "square.grid.2x2.fill" : "square.grid.2x2"))
                    }
                }
                .tag(0)


            // New Listing
            NewListingView()
                .tabItem {
                    VStack {
                        Image(systemName: (selection == 1 ? "plus.square.fill" : "plus.square"))
                    }
                }
                .tag(1)

            // Bag
            BagView()
                .tabItem {
                    VStack {
                        Image(systemName: (selection == 2 ? "bag.fill" : "bag"))
                    }
                }
                .tag(2)

            // Profile
            ProfileView()
                .tabItem {
                    VStack {
                        Image(systemName: (selection == 3 ? "person.crop.square.fill" : "person.crop.square"))
                    }
                }
                .tag(3)
        }.edgesIgnoringSafeArea(.top)
    }
}

问题: 当我点击“New Listing”选项卡时,如何使NewListingView以模态形式(在SwiftUI中称为sheet)显示?

2个回答

7
如果我正确理解了您的目标,您可以考虑以下方法,基于使用Thin Wrapper View的想法,它将以Sheet形式呈现目标视图...
以下是具体步骤:
struct SheetPresenter<Content>: View where Content: View {
    @Binding var presentingSheet: Bool
    var content: Content
    var body: some View {
        Text("")
            .sheet(isPresented: self.$presentingSheet, content: { self.content })
            .onAppear {
                DispatchQueue.main.async {
                    self.presentingSheet = true
                }
            }
    }
}

而对于您的情况,使用方法是...

// New Listing
    SheetPresenter(presentingSheet: $newListingPresented, content: NewListingView())
    .tabItem {
        VStack {
            Image(systemName: (selection == 1 ? "plus.square.fill" : "plus.square"))
        }
    }
    .tag(1)

如果您需要在工作表中完成后更改选项卡selection,则可以在SheetPresenter中传递一些额外的参数,并在工作表的onDismiss: (() -> Void)?回调中使用它。


不错!不过我有一个建议,你可以在SheetPresenter的主体中使用Rectangle组件代替那个空的Text - nayem
谢谢!这很有效。您能否附上一个示例,说明我如何在表单关闭时更改选项卡“选择”? - Steven Schafer
你基本上可以使用任何东西来代替Text或Rectangle。我更喜欢使用Color.clear来实现这个目的。 - ramzesenok

1
我认为您正在寻找this的解决方案。您可以创建一个空的tabItem(Text(" ")),在需要的位置设置Image,并使用.onTapGesture。在那个答案中,我只是展示了如何呈现ActionSheet

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接