问题描述
我不知道这是一个错误还是我在这里做错了什么.我在导航栏上添加了一个新按钮,用于显示新视图.
I don't know if this is a bug or I am doing something wrong here. I've added a new button on the Navigation bar that would present a new view.
struct MyView: View {
@ObservedObject var viewModel = MyViewModel()
var body: some View {
List(viewModel.data, id: \.name) { data in
NavigationLink(destination: MyDetailView(data: data.name)) {
Text(data.name)
}
}
.listStyle(InsetGroupedListStyle())
.edgesIgnoringSafeArea(.all)
.toolbar {
ToolbarItem(placement: .navigationBarTrailing) {
NavigationLink(destination: MyDetailView()) {
Text("New Element")
}
}
}
}
}
正在最新的 iOS 14 beta (beta 6) 和 Xcode 12 (beta 6) 上进行测试.据我所知,导航链接在列表中可以很好地呈现新视图,但在工具栏中,如图所示,情况并非如此.工具栏上的按钮可见且处于活动状态,但不会触发显示新视图.
This is being tested on the newest iOS 14 beta (beta 6) and Xcode 12 (beta 6). As far as I know a Navigation Link presents fine the new view when on a List but in the toolbar as shown that's not the case. The button on the toolbar it's visible and active but doesn't trigger showing the new view.
推荐答案
NavigationLink
应该在 inside NavigationView
.工具栏不在 NavigationView
中,把按钮放在里面.
NavigationLink
should be inside NavigationView
. Toolbar is not in NavigationView
, put buttons in it.
所以假设你在父母的某个地方
So assuming you have somewhere in parent
NavigationView {
MyView()
}
这是一个解决方案:
struct MyView: View {
@ObservedObject var viewModel = MyViewModel()
@State private var showNew = false
var body: some View {
List(viewModel.data, id: \.name) { data in
NavigationLink(destination: MyDetailView(data: data.name)) {
Text(data.name)
}
}
.listStyle(InsetGroupedListStyle())
.background(
NavigationLink(destination: MyDetailView(), isActive: $showNew) {
EmptyView()
}
)
.edgesIgnoringSafeArea(.all)
.toolbar {
ToolbarItem(placement: .navigationBarTrailing) {
Button("New Element") {
self.showNew = true
}
}
}
}
}
这篇关于SwiftUI ToolbarItem 不显示来自 NavigationLink 的视图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!