SwiftUI中NavigationSplitView在iPhone端的自动导航实现
可以通过在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
相关产品推荐
相关产品推荐

