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

SwiftUI中NavigationSplitView在iPhone端的自动导航实现

在NavigationSplitView的iPhone端自动导航至详情视图(无需重构为NavigationStack或单独视图)

可以通过在PlayerList中使用NavigationLink的isPresented绑定,并结合onAppear触发自动跳转的方式实现需求,无需重构整体视图结构,也不用为iPhone和iPad编写单独视图。

修改后的PlayerList代码:

struct PlayerList: View {
    @ObservedObject var game: Game
    @State private var shouldNavigateToScore = false
    @State private var hasAutoNavigated = false // 避免重复自动跳转

    var body: some View {
        VStack {
            TeamNamesView(game: game)
            BattingPlayerList(game: game)
        }
        .toolbar {
            if UIDevice.isIPhone {
                ToolbarItem {
                    // 绑定isPresented控制导航,隐藏按钮(如需保留按钮可移除.hidden())
                    NavigationLink(
                        destination: GameAlertContainerView(game: game),
                        isPresented: $shouldNavigateToScore
                    ) {
                        Text("Score")
                    }
                    .hidden()
                }
            }
        }
        .onAppear {
            // 仅在iPhone上且未自动跳转过时触发导航
            if UIDevice.isIPhone && !hasAutoNavigated {
                shouldNavigateToScore = true
                hasAutoNavigated = true
            }
        }
    }
}

逻辑说明:

  • 在iPhone设备上,NavigationSplitView会自动切换为堆叠导航模式,侧边栏视图作为导航栈的根视图,此时NavigationLink的isPresented绑定可以正常生效(isActive已被弃用,推荐使用isPresented)。
  • 通过.hidden()隐藏原"Score"按钮,但保留NavigationLink在视图层级中,确保导航逻辑正常运行;若希望保留按钮供用户手动触发,直接移除.hidden()即可。
  • 新增hasAutoNavigated状态变量,防止用户从详情视图返回PlayerList后,再次触发自动跳转。

内容的提问来源于stack exchange,提问作者Steve Schwedt

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.20 12:28:14