SwiftUI中NavigationLink点击无响应,需长按跳转的问题解决
SwiftUI列表行点击无响应,仅长按跳转的解决方法
问题场景
我搭建了如下SwiftUI项目结构:
CustomCell.swift
struct CustomCell: View { let title: String let subtitle: String init(title: String, subtitle: String) { self.title = title self.subtitle = subtitle } var body: some View { HStack { Text(title) Spacer() Text(subtitle) } } }
ScreenView.swift
struct ScreenView: View { var body: some View { NavigationStack { List { Section { NavigationLink(destination: Text("message")) { CustomCell(title: "cellTitle", subtitle: "cellSubtitle") } NavigationLink(destination: Text("message")) { CustomCell(title: "cellTitle", subtitle: "cellSubtitle") } } .listRowInsets(EdgeInsets()) } .listStyle(.automatic) } } }
ContentView.swift
struct ContentView: View { @State private var tabIndex = 0 var body: some View { TabView(selection: $tabIndex) { Text("Empty screen") .onTapGesture { tabIndex = 0 } .tabItem { Label("First", systemImage: "circle.fill") } .tag(0) ScreenView() .onTapGesture { tabIndex = 1 } .tabItem { Label("Second", systemImage: "square.fill") } .tag(1) } .tint(.red) .onAppear() { UITabBar.appearance().unselectedItemTintColor = .lightGray } } }
点击列表中的行时,点击操作未被识别,无任何反应,必须长按才能跳转到新页面,如何实现正常的点击跳转行为?
问题原因及解决方法
问题出在ContentView中给ScreenView添加的onTapGesture,这个手势会拦截ScreenView内部所有的点击事件,包括列表行的NavigationLink点击,导致只有长按这种不被拦截的手势才能触发跳转。
解决步骤:
- 移除ScreenView上的
.onTapGesture { tabIndex = 1 },TabView的tabItem本身会处理选中切换,不需要额外添加点击手势设置tabIndex。 - 第一个标签页的
.onTapGesture { tabIndex = 0 }同样可以移除,属于多余设置,TabView会自动管理选中状态。
修改后的ContentView代码:
struct ContentView: View { @State private var tabIndex = 0 var body: some View { TabView(selection: $tabIndex) { Text("Empty screen") .tabItem { Label("First", systemImage: "circle.fill") } .tag(0) ScreenView() .tabItem { Label("Second", systemImage: "square.fill") } .tag(1) } .tint(.red) .onAppear() { UITabBar.appearance().unselectedItemTintColor = .lightGray } } }
修改完成后,列表行的NavigationLink即可正常响应点击跳转。
内容的提问来源于stack exchange,提问作者iOSdeveloper
相关产品推荐
相关产品推荐

