SwiftUI – Adding title between navigation bar button items on a modal

Advertisements

I have a view which I present as a modal view. In this view, I wish to have a button on the top left, another button on the top right and a text horizontally centered between both the buttons. I was able to place the buttons correctly using "navigationBarItems", but it doesn’t allow me to add a text.

Code which just places the buttons correctly, however I am not able to add the text:

import SwiftUI

struct BookingModal: View {
    @Environment(\.presentationMode) var presentationMode
    
    var body: some View {
        NavigationView() {
            VStack {
                Text("Hello World")
            }
            .navigationBarItems(leading: Button("Cancel", action: {presentationMode.wrappedValue.dismiss()}), trailing: Button("Done", action: { }))
        }
    }
}

struct BookingModal_Previews: PreviewProvider {
    static var previews: some View {
        BookingModal()
    }
}

What I attempted: I tried replacing code within "navigationBarItems" with the below:

.navigationBarItems(leading: HStack { Button("Cancel", action: {}); Spacer(); Text("Booking"); Spacer(); Button("Done", action: {})}.frame(width: .infinity))

However with these, all the elements show up on the left, mostly because of leading.

How can I achieve showing the title text horizontally centered between both navigation bar buttons?

>Solution :

You have to use navigationTitle and navigationBarTitleDisplayMode. set navigationBarTitleDisplayMode to inline

struct BookingModal: View {
    @Environment(\.presentationMode) var presentationMode

    var body: some View {
           NavigationView() {
               VStack {
                   Text("Hello World")
               }
               .navigationBarItems(leading: Button("Cancel", action: {presentationMode.wrappedValue.dismiss()}), trailing: Button("Done", action: { }))
               .navigationTitle("Booking")
               .navigationBarTitleDisplayMode(.inline)

           }
       }
}

Leave a ReplyCancel reply