iPadOS 15.5中SwiftUI分栏视图导航随机失效问题求助
在iPadOS 15.5 + Xcode 13.4.1环境下,使用NavigationView配合SidebarListStyle实现的侧边栏导航,在分屏模式的最窄布局中会出现NavigationLink点击无响应的随机失效问题,这是iPadOS 15中NavigationView的已知布局状态管理bug。
问题复现代码
@main struct ipadViewTestsApp: App { var body: some Scene { WindowGroup { NavigationView { List { NavigationLink { Text("About") } label: { Label("About", systemImage: "info.circle") } NavigationLink { Text("Settings") } label: { Label("Settings", systemImage: "gear") } } .listStyle(SidebarListStyle()) .navigationTitle("Sidebar Test") Text("Please make a selection. ") } } } }
解决方案
针对iPadOS 15的兼容场景,推荐两种稳定的解决方式:
方式一:使用列表选择状态直接切换视图
绕开NavigationLink的自动导航栈,通过List的selection绑定追踪选中项,直接在主视图区域切换内容:
@main struct ipadViewTestsApp: App { // 定义选中视图的枚举类型 enum SelectedView: Hashable { case about, settings } @State private var selectedView: SelectedView? var body: some Scene { WindowGroup { NavigationView { List(selection: $selectedView) { Label("About", systemImage: "info.circle") .tag(SelectedView.about) Label("Settings", systemImage: "gear") .tag(SelectedView.settings) } .listStyle(SidebarListStyle()) .navigationTitle("Sidebar Test") // 根据选中项展示对应视图 switch selectedView { case .about: Text("About") case .settings: Text("Settings") case nil: Text("Please make a selection. ") } } } } }
方式二:绑定状态控制导航链接+强制栈式导航
通过isActive绑定手动控制NavigationLink的激活状态,并强制窄布局下使用栈式导航风格,避免系统布局切换时的状态异常:
@main struct ipadViewTestsApp: App { @State private var showAbout = false @State private var showSettings = false var body: some Scene { WindowGroup { NavigationView { List { NavigationLink(isActive: $showAbout) { Text("About") } label: { Label("About", systemImage: "info.circle") } NavigationLink(isActive: $showSettings) { Text("Settings") } label: { Label("Settings", systemImage: "gear") } } .listStyle(SidebarListStyle()) .navigationTitle("Sidebar Test") Text("Please make a selection. ") } // 强制在紧凑布局下使用栈式导航 .navigationViewStyle(StackNavigationViewStyle()) } } }
后续优化建议
若后续项目升级到iPadOS 16及以上版本,建议替换为官方推荐的NavigationSplitView组件,它专门针对侧边栏布局做了优化,从根本上解决这类兼容性问题。
内容的提问来源于stack exchange,提问作者Skk
相关产品推荐
相关产品推荐

