【问题标题】:SwiftUI Present View Modally via TabView?SwiftUI 通过 TabView 模态显示视图?
【发布时间】:2020-04-16 10:14:28
【问题描述】:

我有一个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)
    }
}

问题: 点击时如何让“新列表”选项卡以模态方式呈现 NewListingView(在 SwiftUI 中称为工作表?)?

【问题讨论】:

    标签: ios swift xcode swiftui tabview


    【解决方案1】:

    如果我正确理解了您的目标,您可以考虑以下方法,基于使用事物包装器视图的想法,它将目标视图呈现为工作表......

    这里是:

    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: (() -&gt; Void)? 回调中使用它。

    【讨论】:

    • 不错的一个!不过有一个建议,您可以在SheetPresenter 的正文中使用Rectangle 组件而不是那个空的Text
    • 谢谢!这很好用。您介意附上一个示例,说明我将如何在工作表关闭时更改标签selection
    • 您基本上可以使用任何东西来代替文本或矩形。我更喜欢为此使用Color.clear
    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-04-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-01-20
      • 1970-01-01
      • 1970-01-01
      • 2020-11-06
      相关资源
      最近更新 更多