由于iOS 13.4和带有presentationMode.wrappedValue.dismiss()
的Xcode 11.4存在一些问题,我正在寻找一种替代方法来以编程方式返回。我从MScottWaller找到了这个解决方案:
iOS SwiftUI: pop or dismiss view programmatically
不幸的是,在我的情况下,它不起作用:
struct MasterView: View {
@State private var showDetail = false
var body: some View {
VStack {
Text("MasterView")
.navigationBarItems(trailing: HStack {
NavigationLink(destination: DetailView(showSelf: $showDetail), isActive: $showDetail) {
Image(systemName: "tag")
.padding(.leading, 4)
}
})
}
}
}
struct DetailView: View {
@Binding var showSelf: Bool
var body: some View {
Button(action: {
self.showSelf = false
}) {
Text("Pop")
}
}
}
如果NavigationLink在navigationBarItem内,则无法从DetailView返回。我不知道这是一个错误还是其他原因,导致NavigationLinkItem在NavigationBarItem中无法以相同的方式工作。
作为解决方法,我将此变体与视图内部的空NavigationLink一起使用。它有效,但是我不喜欢这样:
struct MasterView: View {
@State private var showDetail = false
var body: some View {
VStack {
Text("MasterView")
NavigationLink(destination: DetailView(showSelf: $showDetail), isActive: $showDetail) {
EmptyView()
}
.navigationBarItems(trailing: HStack {
Button(action: { self.showDetail.toggle() }) {
Image(systemName: "tag")
.padding(.leading, 4)
}
})
}
}
}
有什么想法为什么NavigationLink无法在navigationBarItem中正常工作?
答案 0 :(得分:1)
这是一个iOS错误。
https://forums.developer.apple.com/thread/125937
解决方法是切换隐藏在导航栏外部的NavigationLink:
struct Parent: View {
@State private var showingChildView = false
var body: some View {
NavigationView {
VStack {
Text("Hello World")
NavigationLink(destination: Child(),
isActive: self.$showingChildView)
{ Text("HiddenLink").hidden() }
}
.navigationBarItems(trailing: Button(action:{ self.showingChildView = true }) { Text("Next") })
}
}
}