我在列表中的 ForEach 内部使用 NavigationLink 来构建一个基本的按钮列表,每个按钮都指向一个单独的详细信息屏幕。
当我点击任何列表单元格时,它会转换到该单元格的详细 View ,但随后会立即弹出回到主菜单屏幕。
不使用 ForEach 有助于避免这种行为,但并不理想。
相关代码如下:
struct MainMenuView: View {
...
private let menuItems: [MainMenuItem] = [
MainMenuItem(type: .type1),
MainMenuItem(type: .type2),
MainMenuItem(type: .typeN),
]
var body: some View {
List {
ForEach(menuItems) { item in
NavigationLink(destination: self.destination(item.destination)) {
MainMenuCell(menuItem: item)
}
}
}
}
// Constructs destination views for the navigation link
private func destination(_ destination: ScreenDestination) -> AnyView {
switch destination {
case .type1:
return factory.makeType1Screen()
case .type2:
return factory.makeType2Screen()
case .typeN:
return factory.makeTypeNScreen()
}
}
最佳答案
如果在 MainMenuView
中有一个 @State
、@Binding
或 @ObservedObject
,主体本身是重新生成(menuItems
再次计算)导致 NavigationLink
无效(实际上是 id
更改)。因此,您不得在详细信息 View 中修改 menuItems
数组 id
-s。
如果它们每次都生成,请考虑设置常量 ID 或存储在非修改部分,例如在 View 模型中。
关于ios - SwiftUI:如果在 ForEach 中使用,NavigationLink 会立即弹出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58302913/