![](/img/trans.png)
[英]SwiftUI List selection binding updates twice on every click, if wrapped in NavigationView (macOS)
[英]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.