[英]How to navigate to a new view from navigationBar button click in SwiftUI
Learning to SwiftUI.学习 SwiftUI。 Trying to navigate to a new view from navigation bar buttton clicked.尝试从单击的导航栏按钮导航到新视图。
The sample code below:示例代码如下:
var body: some View {
NavigationView {
List(0...< 5) { item in
NavigationLink(destination: EventDetails()){
EventView()
}
}
.navigationBarTitle("Events")
.navigationBarItems(trailing:
NavigationLink(destination: CreateEvent()){
Text("Create Event")
}
)
}
}
Three steps got this working for me : first add an @State Bool
to track the showing of the new view :三个步骤对我@State Bool
:首先添加一个@State Bool
来跟踪新视图的显示:
@State var showNewView = false
Add the navigationBarItem, with an action that sets the above property :添加 navigationBarItem,使用设置上述属性的操作:
.navigationBarItems(trailing:
Button(action: {
self.showNewView = true
}) {
Text("Go To Destination")
}
)
Finally add a navigation link somewhere in your view code (this relies on also having a NavigationView somewhere in the view stack)最后在您的视图代码中的某处添加一个导航链接(这依赖于在视图堆栈中的某处也有一个 NavigationView)
NavigationLink(
destination: MyDestinationView(),
isActive: $showNewView
) {
EmptyView()
}.isDetailLink(false)
Put the NavigationLink into the label of a button.将 NavigationLink 放入按钮的标签中。
.navigationBarItems(
trailing: Button(action: {}, label: {
NavigationLink(destination: NewView()) {
Text("")
}
}))
This works for me:这对我有用:
.navigationBarItems(trailing: HStack { AddButton(destination: EntityAddView()) ; EditButton() } )
Where:在哪里:
struct AddButton<Destination : View>: View {
var destination: Destination
var body: some View {
NavigationLink(destination: self.destination) { Image(systemName: "plus") }
}
}
It is an iOS13 bug at the moment: https://forums.developer.apple.com/thread/124757目前这是一个 iOS13 错误: https ://forums.developer.apple.com/thread/124757
The "sort-of" workaround can be found here: https://stackoverflow.com/a/57837007/4514671 “排序”解决方法可以在这里找到: https : //stackoverflow.com/a/57837007/4514671
Here is my solution: MasterView -这是我的解决方案:MasterView -
import SwiftUI
struct MasterView: View {
@State private var navigationSelectionTag: Int? = 0
var body: some View {
NavigationView {
VStack {
NavigationLink(destination: DestinationView(), tag: 1, selection: self.$navigationSelectionTag) {
EmptyView()
}
Spacer()
}
.navigationBarTitle("Master")
.navigationBarItems(trailing: Button(action: {
self.navigationSelectionTag = 1
}, label: {
Image(systemName: "person.fill")
}))
}
}
}
struct MasterView_Previews: PreviewProvider {
static var previews: some View {
MasterView()
}
}
And the DetailsView -和 DetailsView -
import SwiftUI
struct DetailsView: View {
var body: some View {
Text("Hello, Details!")
}
}
struct DetailsView_Previews: PreviewProvider {
static var previews: some View {
DetailsView()
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.