SwiftUI中Button嵌套NavigationLink无法触发跳转问题
问题根因
NavigationLink必须在导航容器的视图层级内才能正常触发跳转:iOS 16 及以上系统使用NavigationStack作为导航容器,iOS 15 及更早版本使用NavigationView。你之前在旧项目中不加导航容器也能运行,是因为当时Intro视图的上层父视图已经被导航容器包裹,代码复制到新项目后,根视图没有挂载导航容器,导航链路断裂,点击自然没有反应。- 你当前将
NavigationLink嵌套在Button内部的写法存在交互冲突:两个组件都是响应点击的可交互元素,嵌套使用会导致事件触发逻辑混乱,即便加上导航容器也可能出现点击无响应、重复触发的问题。
修复步骤
- 在导航链路的最外层视图添加导航容器,只需要加一次即可,不需要在每个子页面重复添加。如果你的App入口直接加载
Intro视图,直接给Intro的最外层套上导航容器就行。 - 删除
NavigationLink外层多余的Button包裹,需要自定义按钮样式时,直接给NavigationLink的标签内容加样式修饰符即可。
修复后代码
import SwiftUI struct Intro: View { var body: some View { // 最外层添加导航容器,低版本iOS可替换为NavigationView NavigationStack { ZStack { VStack { Image("CDM") .resizable() .frame(width: 500, height: 500, alignment: .center) HStack { Text("Welcome to Chatter") .font(.system(size: 45, weight: .semibold, design: .rounded)) .foregroundColor(Color("Yellow")) Image(systemName: "message.fill") .font(.system(size: 45)) .foregroundColor(Color("Yellow")) .padding() } Text(""" Note: This experience is best viewed in Horizontal """) .font(.system(size: 30, weight: .semibold, design: .rounded)) .foregroundColor(.secondary) .padding() // 移除外层多余的Button,直接使用NavigationLink NavigationLink(destination: Intro2()) { Text("Next") .font(.system(size: 30, weight: .semibold ,design: .rounded)) .foregroundColor(.white) .padding() .background(Color("Purple")) .cornerRadius(20) } } } } } } struct Intro2: View { var body: some View { VStack { Text("What you can do in this experience") // 移除外层多余的Button NavigationLink(destination: Main()) { HStack { Text("Click here to get started!") .font(.system(size: 25, weight: .regular ,design: .rounded)) .foregroundColor(.white) .padding() .background(Color("Purple")) .cornerRadius(20) } } } } }
注意:不要在
Intro2、Main等后续子页面中重复添加导航容器,否则会出现导航栏堆叠、返回手势失效的问题。
内容的提问来源于stack exchange,提问作者54Hex
相关产品推荐
相关产品推荐

