我正在努力为 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()
}
tabSelection
中的比较是向后的。
if newValue == activeTab {
应该是
!=
。