SwiftUI 中 NavigationView 导航栏的自定义后退按钮 [英] Custom back button for NavigationView's navigation bar in SwiftUI

查看:79
本文介绍了SwiftUI 中 NavigationView 导航栏的自定义后退按钮的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想添加一个看起来有点像这样的自定义导航按钮:

I want to add a custom navigation button that will look somewhat like this:

现在,我为此编写了一个自定义的 BackButton 视图.将该视图应用为导航栏项时,执行以下操作:

Now, I've written a custom BackButton view for this. When applying that view as leading navigation bar item, by doing:

.navigationBarItems(leading: BackButton())

...导航视图如下所示:

...the navigation view looks like this:

我使用过如下修饰符:

.navigationBarItem(title: Text(""), titleDisplayMode: .automatic, hidesBackButton: true)

运气不好.

我怎么能...

  1. 在导航栏中设置一个用作自定义后退按钮的视图?或:
  2. 以编程方式将视图弹回其父级?
    在采用这种方法时,我可以使用 .navigationBarHidden(true)
  3. 完全隐藏导航栏
  1. set a view used as custom back button in the navigation bar? OR:
  2. programmatically pop the view back to its parent?
    When going for this approach, I could hide the navigation bar altogether using .navigationBarHidden(true)

推荐答案

TL;DR

使用它来转换您的视图:

NavigationLink(destination: SampleDetails()) {}

将此添加到视图本身:

@Environment(\.presentationMode) var presentationMode: Binding<PresentationMode>

然后,在按钮操作或其他操作中,关闭视图:

Then, in a button action or something, dismiss the view:

presentationMode.wrappedValue.dismiss()


完整代码

从父母那里,使用 NavigationLink

 NavigationLink(destination: SampleDetails()) {}

在DetailsView中隐藏navigationBarBackButton并将自定义后退按钮设置为前导navigationBarItem

In DetailsView hide navigationBarBackButton and set custom back button to leading navigationBarItem,

struct SampleDetails: View {
    @Environment(\.presentationMode) var presentationMode: Binding<PresentationMode>

    var btnBack : some View { Button(action: {
        self.presentationMode.wrappedValue.dismiss()
        }) {
            HStack {
            Image("ic_back") // set image here
                .aspectRatio(contentMode: .fit)
                .foregroundColor(.white)
                Text("Go back")
            }
        }
    }
    
    var body: some View {
            List {
                Text("sample code")
        }
        .navigationBarBackButtonHidden(true)
        .navigationBarItems(leading: btnBack)
    }
}

这篇关于SwiftUI 中 NavigationView 导航栏的自定义后退按钮的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆