SwiftUI中List的ForEach循环内无法通过代码激活NavigationLink
在我的测试项目中,我实现了一个由NavigationLink项组成的List:
GamesViewModel.swift文件模拟了数值型游戏ID列表,在我的实际应用中这类ID是通过Websockets下发的:
class GamesViewModel: ObservableObject /*, WebSocketDelegate */ { @Published var currentGames: [Int] = [2, 3] @Published var displayedGame: Int = 0 func updateCurrentGames() { currentGames = currentGames.count == 3 ? [1, 2, 3, 4] : [2, 5, 7] } func updateDisplayedGame() { displayedGame = currentGames.randomElement() ?? 0 } }
我的需求是,点击“Join a random game”按钮时,在ContentView.swift中通过代码激活一个随机的NavigationLink,初始代码如下:
struct ContentView: View { @StateObject private var vm:GamesViewModel = GamesViewModel() var body: some View { NavigationView { VStack { List { ForEach(vm.currentGames, id: \.self) { gameNumber in NavigationLink(destination: GameView(gameNumber: gameNumber) /* , isActive: $vm.displayedGame == gameNumber */ ) { Text("Game #\(gameNumber)") } } } Button( action: { vm.updateCurrentGames() }, label: { Text("Update games") } ) Button( action: { vm.updateDisplayedGame() }, label: { Text("Join a random game") } ) } } } }
但如下写法无法通过编译:
ForEach(vm.currentGames, id: \.self) { gameNumber in NavigationLink(destination: GameView(gameNumber: gameNumber), isActive: $vm.displayedGame == gameNumber ) { Text("Game #\(gameNumber)") } }
报错信息为:
Cannot convert value of type 'Bool' to expected argument type 'Binding'
请问是否可以在ForEach内部使用$符号?
我的实际业务场景是:Jetty后端在PostgreSQL数据库中创建新游戏后,会将该新游戏的数字ID发送给客户端,应用需要自动展示该游戏,也就是通过代码导航到GameView.swift页面。
问题更新
已有的解决方案仅适用于较短的List,即所有NavigationLink都在屏幕可见范围内的场景。
如果List较长,待激活的NavigationLink对应的游戏编号已经滚动到屏幕外时,这些方案就会失效!
我尝试自行实现方案:在屏幕顶部添加一个绑定EmptyView的NavigationLink,确保它始终可见,可以被触发跳转到对应vm.displayedGame编号的页面。但是我的代码仅能生效一次,无法正常运行,ContentView.swift代码如下:
struct ContentView: View { @StateObject private var vm:GamesViewModel = GamesViewModel() var body: some View { NavigationView { VStack { NavigationLink( destination: GameView(gameNumber: vm.displayedGame), isActive: Binding(get: { vm.displayedGame > 0 }, set: { _,_ in }) ) { EmptyView() } List { ForEach(vm.currentGames, id: \.self) { gameNumber in NavigationLink( destination: GameView(gameNumber: gameNumber) ) { Text("Game #\(gameNumber)") } } } Button( action: { vm.updateCurrentGames() }, label: { Text("Update games") } ) Button( action: { vm.updateDisplayedGame() }, label: { Text("Join a random game") } ) } } } }
1. 初始编译报错的原因
isActive参数要求接收的是Binding<Bool>类型,你直接写$vm.displayedGame == gameNumber得到的是普通Bool值,自然会报类型不匹配的错误。但这种绑定到List内部NavigationLink的方案在元素滚出屏幕后会失效,因此不推荐使用。
2. 修复全局NavigationLink只生效一次的问题
你的思路是正确的,用始终存在的全局NavigationLink处理代码触发的跳转,失效的原因是你没有处理Binding的setter逻辑,跳转返回后没有把displayedGame重置为0,导致下一次displayedGame变化时系统不会识别到状态更新,因此不会触发第二次跳转。
修改后的代码如下:
首先调整GamesViewModel,增加重置逻辑:
class GamesViewModel: ObservableObject /*, WebSocketDelegate */ { @Published var currentGames: [Int] = [2, 3] @Published var displayedGame: Int = 0 func updateCurrentGames() { currentGames = currentGames.count == 3 ? [1, 2, 3, 4] : [2, 5, 7] } func updateDisplayedGame() { displayedGame = currentGames.randomElement() ?? 0 } // 新增重置显示游戏的方法 func resetDisplayedGame() { displayedGame = 0 } }
然后修改ContentView中的NavigationLink绑定逻辑:
struct ContentView: View { @StateObject private var vm:GamesViewModel = GamesViewModel() var body: some View { NavigationView { VStack { // 修复后的全局NavigationLink NavigationLink( destination: GameView(gameNumber: vm.displayedGame) .onDisappear { // 返回主页时重置displayedGame,下次可再次触发跳转 vm.resetDisplayedGame() }, isActive: Binding( get: { vm.displayedGame > 0 }, set: { isActive in // 手动拖拽返回时也同步重置状态 if !isActive { vm.resetDisplayedGame() } } ) ) { EmptyView() } List { ForEach(vm.currentGames, id: \.self) { gameNumber in NavigationLink( destination: GameView(gameNumber: gameNumber) ) { Text("Game #\(gameNumber)") } } } Button( action: { vm.updateCurrentGames() }, label: { Text("Update games") } ) Button( action: { vm.updateDisplayedGame() }, label: { Text("Join a random game") } ) } } } }
补充说明
- 这种全局单个NavigationLink的方案不受List长度限制,不管目标ID是否在当前List可见范围内都可以正常跳转
- 如果你使用的是iOS 16及以上系统,更推荐用
NavigationStack搭配navigationDestination修饰符实现,代码会更简洁,不需要额外维护单独的NavigationLink
内容的提问来源于stack exchange,提问作者Alexander Farber

