【发布时间】:2021-12-15 18:57:27
【问题描述】:
在simple test project at Github 中,我显示一个 NavigationLink 项目列表:
GamesViewModel.swift 文件模拟了一个数字游戏 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
}
}
我的问题是,当单击“加入随机游戏”按钮时,我试图以编程方式激活 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)")
}
}
无法编译:
无法将类型“Bool”的值转换为预期的参数类型“Binding”
甚至可以在ForEach 中使用$ 吗?
我的上下文是,在我的真实应用程序中,Jetty 后端在 PostgreSQL 数据库中创建一个新游戏,然后将该新游戏的数字 id 发送到应用程序。并且应用程序应该显示该游戏,即以编程方式导航到 GameView.swift。
更新:
用户 jnpdx 和 Dhaval 都提出了有趣的解决方案(谢谢!) - 但是当 NavigationLink 在屏幕上可见时,它们仅适用于短列表。
对于更长的列表,当应为滚动到屏幕外的游戏编号激活 NavigationLink 时 - 它们不起作用!
我已经尝试实现自己的解决方案,通过在屏幕顶部使用 NavigationLink/EmptyView,以确保它始终可见并且可以被触发以转换到 vm.displayedGame 号码。
但是我的代码不起作用,即只能工作一次(也许我需要在导航回主屏幕后以某种方式设置displayedGame = 0?)-
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") }
)
}
}
}
}
【问题讨论】:
标签: ios swift swiftui swiftui-navigationlink swiftui-navigationview