按下选项卡栏图标时,无法在 SwiftUI 中使用 NavigationStack 弹出到根目录

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

我正在努力为 SwiftUI 中的选项卡栏视图实现弹出到根视图。使用我当前的代码,我可以在第一次点击后的每次点击时打印

newValue
。该代码按预期工作,但不会重置给定选项卡的 NavigationStack。我在这里缺少什么吗?

这是代码,它基于我找到的更多上下文视频。 视频

import SwiftUI

struct TabViews: View {
    
    enum Tab {
        case friends, home, profile
    }
    
    @State private var activeTab: Tab = .home
    @State private var friendsStack: NavigationPath = .init()
    @State private var homeStack: NavigationPath = .init()
    @State private var profileStack: NavigationPath = .init()
    
    var body: some View {
        TabView(selection: tabSelection) {
            Group {
                NavigationStack(path: $friendsStack) {
                    Text("Friends")
                }
                .tabItem {
                    Image("FriendsTabIcon")
                }
                .tag(Tab.friends)
                
                NavigationStack(path: $homeStack) {
                    Text("Home")
                }
                .tabItem {
                    Image("HomeTabIcon")
                }
                .tag(Tab.home)
                
                NavigationStack(path: $profileStack) {
                    Text("Profile")
                }
                .tabItem {
                    Image("ProfileTabIcon")
                }
                .tag(Tab.profile)
            }
            .toolbarBackground(.visible, for: .tabBar)
            .toolbarBackground(.brandBackground, for: .tabBar)
        }
    }
    
    var tabSelection: Binding<Tab> {
        return .init {
            return activeTab
        } set: { newValue in
            if newValue == activeTab {
                print(newValue)
                switch newValue {
                case .friends: friendsStack = .init()
                case .home: homeStack = .init()
                case .profile: profileStack = .init()
                }
            }
            activeTab = newValue
        }
    }
}

#Preview {
    TabViews()
}
ios swift swiftui mobile
1个回答
0
投票

tabSelection
中的比较是向后的。

            if newValue == activeTab {

应该是

!=

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