[英]SwiftUI - Navigation Link opening the same view multiple times
我在 ViewA 中有一個包含 3 行的列表。 ViewA 是主視圖的孫子(不確定此信息是否重要,但只是提供,因為我不知道實際的錯誤在哪里。這是堆棧的內容視圖 -> 打開主菜單視圖(MMV) - > 從 MMV 中選擇一個項目並打開 -> 設置視圖 -> 從設置中選擇一個項目並打開 ViewA)。
當我單擊 ViewA 中的一行時,應該會打開另一個視圖,比如說 ViewB。 但是我看到 ViewB 實例化 3 次,即我看到 ViewB 在屏幕上出現 3 次,然后它在最后一個實例停止。
我不確定為什么會發生這種情況以及實際的錯誤是什么。 這是我的代碼:
視圖A(菜單視圖選項):
struct MenuViewOptions: View {
@State var destination: MenuViewType?
var isActive: Binding<Bool> { Binding(get: { destination != nil }, set: { _ in destination = nil } ) }
var body: some View {
VStack {
List(SettingsOptions().menuViewSettingsOptions) { item in
NavigationLink(isActive: isActive, destination: {destination?.view} ) {
MenuViewOptionRowView(menuViewItem: item, destination: $destination)
}
}
}.navigationBarTitle("Settings")
}
}
菜單視圖類型代碼:
enum MenuViewType: Int, CaseIterable, Hashable {
case circularGrid = 0, regularList = 1, capsuleGrid = 2
@ViewBuilder var view: some View {
switch self {
case .circularGrid: MainMenuCircularGridViewNew()
case .regularList: MainMenuListView()
case .capsuleGrid: MainMenuCapsuleGridView()
}
}
}
SettingsOptions().menuViewSettingsOptions 代碼:
struct SettingsOptions {
// View inside menu view settings
let menuViewSettingsOptions: [MenuViewSettingsItem] = [
MenuViewSettingsItem(id: 0, name: "Circular Grid", imageName: "circle.grid.2x2", isSelected: false),
MenuViewSettingsItem(id: 1, name: "List", imageName: "list.dash", isSelected: false),
MenuViewSettingsItem(id: 2, name: "Capsule Grid", imageName: "rectangle.grid.2x2", isSelected: false),
]
}
MenuViewOptionRow查看代碼
struct MenuViewOptionRowView: View {
let menuViewItem: MenuViewSettingsItem
@ObservedObject var userSettingsStore = UserSettingsStore()
@Binding var destination: MenuViewType?
var body: some View {
HStack {
Image(systemName: menuViewItem.imageName)
.circularImageStyle(width: 15, height: 15, padding: 5, backgroundColor: Color(red: 34 / 255, green: 34 / 255, blue: 34 / 255), foregroundColor: Color(red: 23 / 255, green: 121 / 255, blue: 232 / 255))
Text(menuViewItem.name)
Spacer()
if menuViewItem.id == userSettingsStore.menuViewSelection {
Image(systemName: "checkmark").foregroundColor(Color(red: 23 / 255, green: 121 / 255, blue: 232 / 255))
}
}.onTapGesture {
userSettingsStore.menuViewSelection = self.menuViewItem.id
destination = MenuViewType(rawValue: self.menuViewItem.id)
}
}
}
基本上我在 MenuViewOptionRowView 中設置目標,一旦設置,MenuViewOptions 中的 isActive 變為 true 並且 NavigationLink 被觸發。 我看到該行導航到正確的視圖,但只是視圖實例化了 3 次,我不確定是否是因為列表中有 3 行。
如果您對可能是什么問題有任何想法,請告訴我。 SwiftUI 的新手。
謝謝!
您設置了一次目的地,但這樣您就激活了 List 中的所有鏈接,因為它們都綁定到一個isActive
。
有了這樣的代碼設計,我會提出以下解決方案:一個目的地 - 一個鏈接,目的地已經設置好,所以......(有問題的代碼不可測試,所以原樣)
List(SettingsOptions().menuViewSettingsOptions) { item in
MenuViewOptionRowView(menuViewItem: item, destination: $destination)
}
.background(
NavigationLink(isActive: isActive, destination: {destination?.view} ) {
EmptyView()
}
)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.