在 SwiftUI 中更改选项卡时,TabView tabBar 会重新出现

问题描述 投票:0回答:1

我无法将

tabBar
隐藏在 SwiftUI 中,例如:

struct ContentView: View {
    @State private var tabIndex = 0

    var body: some View {
        TabView(selection: $tabIndex) {
            View1()
                .ignoresSafeArea()
                .toolbar(.hidden, for: .tabBar)
                .tag(0)

            Color.white
                .ignoresSafeArea()
                .toolbar(.hidden, for: .tabBar)
                .tag(1)
        }
        .overlay(alignment: .bottomLeading) {
            Button("Tap") {
                if tabIndex == 0 {
                    tabIndex = 1
                } else {
                    tabIndex = 0
                }
            }
            .padding()
        }
    }
}

struct View1: View {
    let data = Array(0..<20)
    var body: some View {
        ScrollView {
            LazyVStack {
                ForEach(data, id: \.self) { _ in
                    Rectangle()
                        .fill(.red)
                        .frame(width: 100.0, height: 100.0)
                }
            }
        }
    }
}

在应用程序启动时,

tabBar
按预期隐藏,更改为第二个选项卡没有问题并且也被隐藏,但是当我改回第一个选项卡并且对于所有后续更改返回第一个选项卡时,
tabBar
显示再次。它似乎与
ScrollView
有关,因为如果我删除它,问题就会消失。不知道当
ScrollView
存在时如何将其隐藏。我怎样才能解决这个问题?任何指点将不胜感激。

swift swiftui
1个回答
0
投票

如果您不希望选项卡栏可见,我建议首先不要使用

TabView
。将所有选项卡放在
ZStack
中并使用
opacity
控制哪些选项卡可见:

ZStack {
    View1()
        .ignoresSafeArea()
        .opacity(tabIndex == 0 ? 1 : 0)

    Color.white
        .ignoresSafeArea()
        .opacity(tabIndex == 1 ? 1 : 0)
}

否则,还有很多其他隐藏选项卡栏的替代方法,您可以在这篇文章中找到。使用 SwiftUI-Introspect 的解决方案适用于这种情况。

.introspect(.tabView, on: .iOS(.v17)) { tabController in
    tabController.tabBar.isHidden = true
}

不过,您必须指定您希望在其上进行内省的 iOS 版本。希望

toolbar(.hidden)
在 iOS 18 中得到修复:)

© www.soinside.com 2019 - 2024. All rights reserved.