[英]Creating a custom back button with NavigationView on SwiftUI
I'm trying to create a custom back button on SwiftUI, but I can't figure out how to do it.我正在尝试在 SwiftUI 上创建一个自定义后退按钮,但我不知道该怎么做。
The idea is to hide the "Back" button at the top left that provides NavigationView, and make a custom button with the same functionality.想法是隐藏左上角提供 NavigationView 的“后退”按钮,并制作一个具有相同功能的自定义按钮。
struct AnadirDatosViewA: View {
@Environment(\.presentationMode) var presentation
var body: some View{
NavigationView(){
Color(red: 48 / 255, green: 49 / 255, blue: 54 / 255)
.edgesIgnoringSafeArea(.all)
.overlay(
VStack{
AnadirDatosExpB()
HStack{
NavigationLink(destination:NuevoExperimentoView()){
Text("Back") //HERE
NavigationLink(destination:AnadirDatosExpA()){
Text("Next")
}
}
}
}
)
}.navigationBarBackButtonHidden(true)
}
}
Right now I'm "cheating" by using the view I want go go back as destination, but it doesn't work the same...现在我通过使用我想要的视图 go go 作为目的地来“作弊”,但它的工作方式不同......
What can I do?我能做什么?
You can use the presentationMode
var from the environment inside a Button:您可以在 Button 内的环境中使用presentationMode
变量:
See the commented example below for a possible implementation.有关可能的实现,请参见下面的注释示例。
struct ContentView: View{
var body: some View{
// I am navigating with a Navigationlink, so there is
// no need for it in the AnadirDatosViewA
NavigationView {
NavigationLink("show AnadirDatosViewA") {
AnadirDatosViewA()
}
}
}
}
struct AnadirDatosViewA: View {
@Environment(\.presentationMode) var presentation
var body: some View{
// if you navigated to this by a Navigationlink remove the NavigationView
Color(red: 48 / 255, green: 49 / 255, blue: 54 / 255)
.edgesIgnoringSafeArea(.all)
.overlay(
HStack{
// This Button will dismiss the View
Button("Back"){
// with help of th presentationMode from the environment
presentation.wrappedValue.dismiss()
}
// This NavigationLink can forward you to another view
NavigationLink("Next") {
TextView(text: "last")
}
}
// This will hide the back Button in this View
).navigationBarBackButtonHidden(true)
}
}
// HelperView
struct TextView: View{
var text: String
var body: some View{
Text(text)
}
}
It seems like presentationMode is going to be deprecated in the future, so instead you could also do似乎 presentationMode 将来会被弃用,所以你也可以这样做
@Environment(\.dismiss) var dismiss
paired with配对
Button(action: {
dismiss()
}, label: {
Image(systemName: "chevron.left")
Text(bookClub.bookTitle)
.fontWeight(.bold)
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.