You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.30 03:11:04