[英]Creating a custom back button with NavigationView on SwiftUI
我正在尝试在 SwiftUI 上创建一个自定义后退按钮,但我不知道该怎么做。
想法是隐藏左上角提供 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)
}
}
现在我通过使用我想要的视图 go go 作为目的地来“作弊”,但它的工作方式不同......
我能做什么?
您可以在 Button 内的环境中使用presentationMode
变量:
有关可能的实现,请参见下面的注释示例。
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)
}
}
似乎 presentationMode 将来会被弃用,所以你也可以这样做
@Environment(\.dismiss) var dismiss
配对
Button(action: {
dismiss()
}, label: {
Image(systemName: "chevron.left")
Text(bookClub.bookTitle)
.fontWeight(.bold)
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.