Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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()
    }
}

enter image description here

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

enter image description here

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)

           }
       }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading