Custom back button for NavigationView's navigation bar in SwiftUI

后端 未结 9 711
隐瞒了意图╮
隐瞒了意图╮ 2020-11-29 23:57

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

Now, I\'ve written a custom BackButton view for this. When applying

9条回答
  •  野趣味
    野趣味 (楼主)
    2020-11-30 00:29

    SwiftUI 1.0

    It looks like you can now combine the navigationBarBackButtonHidden and .navigationBarItems to get the effect you're trying to achieve.

    Code

    struct Navigation_CustomBackButton_Detail: View {
        @Environment(\.presentationMode) var presentationMode
        
        var body: some View {
            ZStack {
                Color("Theme3BackgroundColor")
                VStack(spacing: 25) {
                    Image(systemName: "globe").font(.largeTitle)
                    Text("NavigationView").font(.largeTitle)
                    Text("Custom Back Button").foregroundColor(.gray)
                    HStack {
                        Image("NavBarBackButtonHidden")
                        Image(systemName: "plus")
                        Image("NavBarItems")
                    }
                    Text("Hide the system back button and then use the navigation bar items modifier to add your own.")
                        .frame(maxWidth: .infinity)
                        .padding()
                        .background(Color("Theme3ForegroundColor"))
                        .foregroundColor(Color("Theme3BackgroundColor"))
                    
                    Spacer()
                }
                .font(.title)
                .padding(.top, 50)
            }
            .navigationBarTitle(Text("Detail View"), displayMode: .inline)
            .edgesIgnoringSafeArea(.bottom)
            // Hide the system back button
            .navigationBarBackButtonHidden(true)
            // Add your custom back button here
            .navigationBarItems(leading:
                Button(action: {
                    self.presentationMode.wrappedValue.dismiss()
                }) {
                    HStack {
                        Image(systemName: "arrow.left.circle")
                        Text("Go Back")
                    }
            })
        }
    }
    

    Example

    Here is what it looks like (excerpt from the "SwiftUI Views" book):

提交回复
热议问题