SwiftUI解决MatchDetailsView嵌套跳转双导航栏问题
SwiftUI嵌套跳转双导航栏问题解决
问题核心
MatchDetailsView内部嵌套了NavigationView,而NavigationLink的跳转依赖上层已有的导航栈,重复添加NavigationView导致每次跳转都新增一个导航栏,出现双导航栏的情况。
解决方案
1. 移除MatchDetailsView中的NavigationView
删除MatchDetailsView里的NavigationView,所有跳转由顶层导航容器统一管理:
struct MatchDetailsView: View { var namespace: Namespace.ID let matchID: Int let homeTeamName: String let awayTeamName: String @ObservedObject var matchViewModel: MatchViewModel // 补充你原有的视图模型属性 var body: some View { List { ScrollView(showsIndicators: false) { HighlightsView(matchViewModel: matchViewModel) MOTMView(matchViewModel: matchViewModel) EventsView(matchViewModel: matchViewModel) MatchStats(matchViewModel: matchViewModel) MatchTopPlayers(matchViewModel: matchViewModel) TeamFormView(matchViewModel: matchViewModel, namespace: namespace) } } .toolbar { ShareLink(item: URL(string: "https://maykmayk.github.io/Balun/#/match-details/\(matchID)")!) { Label("", systemImage: "square.and.arrow.up") } Button { // 执行对应操作 } label: { Image(systemName: "bell") } Button { // 执行对应操作 } label: { Image(systemName: "star") } } .toolbarRole(.editor) .tint(Color(.textAccent)) .navigationTitle("\(homeTeamName) vs \(awayTeamName)") } }
2. 确保顶层存在导航容器
在包含MatchListView的父视图中添加顶层导航容器(iOS 16+用NavigationStack,iOS 15及以下用NavigationView):
struct MainView: View { @Namespace var namespace var body: some View { NavigationStack { // iOS 15及以下替换为NavigationView MatchListView(namespace: namespace) } } }
3. 保留TeamFormView的NavigationLink逻辑
TeamFormView中的NavigationLink无需修改,现在所有跳转都在顶层导航栈中进行,跳转后只会更新现有导航栏的标题和返回按钮,不会生成新的导航栏。
效果说明
修改完成后,无论是从MatchListView进入MatchDetailsView,还是从TeamFormView跳转到另一个MatchDetailsView,顶部只会显示一个导航栏,符合预期效果。
内容的提问来源于stack exchange,提问作者Michele de Vita
相关产品推荐
相关产品推荐

