簡體   English   中英

SwiftUI:在 macOS 下具有編程選擇的 NavigationView/List

[英]SwiftUI: NavigationView/List with programmatic selection under macOS

我有一個允許編程選擇的 NavigationView/List 組合。 基本概念類似於此處描述的概念: https://www.hackingwithswift.com/quick-start/swiftui/how-to-use-programmatic-navigation-in-swiftui

有這么多東西,這在 iOS 上工作正常,但在 macOS 上有一個問題:一旦選擇了一個項目,NavigationView 中的 EmptyView 就會變得可見:

在此處輸入圖像描述

有人知道如何刪除這個不需要的 EmptyView() 嗎?

這是一個演示項目:

struct ContentView: View {
    @ObservedObject private var state = State()

    var body: some View {
        NavigationView {
            VStack {
                List(state.items, id: \.self, selection: $state.selected) { item in
                    Text(item)
                        .buttonStyle(.borderless)
                }

                // navigation to the detail view if an item is selected
                if let selected = state.selected {
                    NavigationLink(
                        destination: Text(selected),
                        isActive: state.hasSelectionBinding
                    ) {
                        EmptyView()
                    }
                }
            }
        }
    }
}

class State: ObservableObject {
    @Published var items: [String] = ["Item 1", "Item 2", "Item 3"]
    @Published var selected: String?

    var hasSelectionBinding: Binding<Bool> {
        Binding(
            get: { self.selected != nil },
            set: {
                if $0 == false {
                    self.selected = nil
                }
            }
        )
    }
}

編輯 1:我嘗試將 NavigationLink 放入堆棧的背景修飾符中,但現在“Empty View”出現在“Item 3”旁邊:

    var body: some View {
        NavigationView {
            VStack {
                List(state.items, id: \.self, selection: $state.selected) { item in
                    Text(item)
                        .buttonStyle(.borderless)
                }
                
            }
            .background(Group {
                // navigation to the detail view if an item is selected
                if let selected = state.selected {
                    NavigationLink(
                        destination: Text(selected),
                        isActive: state.hasSelectionBinding
                    ) {
                        EmptyView()
                    }
                }
                
            })
        }
    }

您可以在您的第一個ContentView代碼中嘗試此解決方法:

NavigationLink("",                // <--- here
    destination: Text(selected),
    isActive: state.hasSelectionBinding
).position(x: 9999, y: 9999)     // <--- here

不需要EmptyView() 請注意,我建議您將State重命名為 model,因為 SwiftUI 已經有一個State結構。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM