SwiftUI中TabView搭配tabViewStyle(.page)导航异常问题
SwiftUI TabView 页面切换异常问题
测试SwiftUI的TabView搭配PageTabViewStyle时遇到异常:应用启动默认显示HomeScreen()符合预期,但点击顶部导航栏的Profile按钮时,仅按钮文字变红(说明pageIndex已更新),TabView却未同步切换到ProfileScreen。但如果先点击Settings按钮或手动滑动页面切换后,再点击Profile按钮就能正常导航,页面滑动切换本身无异常。
复现步骤
- 将代码复制到Xcode
- 在模拟器/画布/真机运行
- 直接点击Profile按钮(不要滑动或点击其他按钮)
- 观察到Profile文字变红,但页面未切换到ProfileScreen
- 若先点击Settings或滑动页面,后续点击Profile可正常切换
原代码
import SwiftUI struct SwipeNavigation2: View { @State var pageIndex = 1 var body: some View { NavigationView { TabView(selection: self.$pageIndex) { // The screen to the "left" of the Home screen ProfileScreen() .tag(0) // The screen we want the app to load on HomeScreen() .tag(1) // The screen to the "right" of the Home screen SettingsScreen() .tag(2) } .tabViewStyle(PageTabViewStyle(indexDisplayMode: .never)) .navigationTitle("") .navigationBarTitleDisplayMode(.inline) .toolbar { ToolbarItem(placement: .navigationBarLeading) { Button { withAnimation(.spring()) { pageIndex = 0 } } label: { Text("Profile") .foregroundColor(pageIndex == 0 ? .red : .primary) } } ToolbarItem(placement: .navigationBarTrailing) { Button { withAnimation(.spring()) { pageIndex = 2 } } label: { Text("Settings") .foregroundColor(pageIndex == 2 ? .red : .primary) } } } } } } private struct ProfileScreen: View { var body: some View { Text("Profile screen") } } private struct HomeScreen: View { var body: some View { Text("Home screen") } } private struct SettingsScreen: View { var body: some View { Text("Settings screen") } }
修改后的代码
struct SwipeNavigation2: View { @State var pageIndex = 0 var body: some View { NavigationView { TabView(selection: self.$pageIndex) { ProfileScreen() .tag(0) HomeScreen() .tag(1) SettingsScreen() .tag(2) } .onAppear { pageIndex = 1 } .tabViewStyle(PageTabViewStyle(indexDisplayMode: .never)) .navigationTitle("") .navigationBarTitleDisplayMode(.inline) .toolbar { ToolbarItem(placement: .navigationBarLeading) { Button { withAnimation(.spring()) { pageIndex = 0 } } label: { Text("Profile") .foregroundColor(pageIndex == 0 ? .red : .primary) } } ToolbarItem(placement: .navigationBarTrailing) { Button { withAnimation(.spring()) { pageIndex = 2 } } label: { Text("Settings") .foregroundColor(pageIndex == 2 ? .red : .primary) } } } } } }
补充测试细节
- 在Xcode14.1的iPhone14模拟器中可复现该问题:点击Profile后文字变红,但页面未切换
- 设备表现差异:
- iPhone13/13 Mini/14:问题存在
- iPhone14 Pro/14 Pro Max:功能正常
内容的提问来源于stack exchange,提问作者ragavanmonke
相关产品推荐
相关产品推荐

