SwiftUI侧栏列表未注册首次点击

时间:2019-11-10 01:30:12

标签: swift macos swiftui navigationlink

使用SwiftUI,我在 Mac应用中具有侧边栏导航来更改视图。单击侧边栏中的项目会更改右侧的视图。但是,启动应用程序时,侧栏List不会注册第一次点击。单击两次即可选择一个项目。之后,边栏将按应有的方式运行,只需单击一下即可更改视图。

如何使用List解决此初始启动问题?

sidebar navigation

import SwiftUI

struct DetailView: View {

    var selection: String

    var body: some View {
        containedView()
    }

    private func containedView() -> AnyView {
        switch selection {
        case "? Apple":
            return AnyView(AppleView())
        case "? Banana":
            return AnyView(BananaView())
        case "? Coconut":
            return AnyView(CoconutView())
        default:
            return AnyView(Text("Some view here").frame(maxWidth: .infinity, maxHeight: .infinity))
        }
    }
}

struct SidebarView: View {

    let items = ["? Apple", "? Banana", "? Coconut", "? Cherry", "? Peanut", "? Peach", "? Tomato", "? Bread", "? Pizza", "? Broccoli", "? Kiwi", "? Cheese", "? Watermelon"]

    var body: some View {
        List(items, id: \.self) { item in
            NavigationLink(destination: DetailView(selection: item)) {
                Text("\(item)")
            }
        }
        .listStyle(SidebarListStyle())
    }
}

struct ContentView: View {
    var body: some View {
        NavigationView {
            SidebarView()
            DetailView(selection: "? Apple")
        }
        .frame(height: 300)
    }
}

1 个答案:

答案 0 :(得分:1)

需要为列表添加选择,如下所示

@State var current = Set<String>()
var body: some View {
    List(items, id: \.self, selection: $current) { item in
        NavigationLink(destination: DetailView(selection: item)) {
            Text(item)
        }
    }
    .listStyle(SidebarListStyle())
}