Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to align a SwiftUI navigationBarTitle to be centered?

How does one centre a navigation bar title in SwiftUI?

var body: some View {
    NavigationView {
        .navigationBarTitle("Todo Lists")
    }
}
like image 908
Greg Avatar asked Aug 13 '19 22:08

Greg


3 Answers

.navigationBarTitle allows for three display modes - .large, .inline, and .automatic.

From the documentation:

case automatic

Inherit the display mode from the previous navigation item.

case inline

Display the title within the standard bounds of the navigation bar.

case large

Display a large title within an expanded navigation bar.

So it depends what you mean when you say "how does one centre a navigation bar title in SwiftUI?" You cannot center a navigation bar title that has a display mode of .large. You also cannot left-align or right-align a navigation bar title that has a display mode of .inline. If you want a navigation bar title that is centered, then your only option is to use .inline.

var body: some View {
    NavigationView {
        CustomView()
            .navigationBarTitle("Todo Lists", displayMode: .inline)
    }
}
like image 124
graycampbell Avatar answered Oct 19 '22 07:10

graycampbell


Also, an awesome approach was shown here.

It's perfect when you need to customize navbar. Keyword .principal is for positioning

NavigationView {
    Text("Hello, SwiftUI!")
        .navigationBarTitleDisplayMode(.inline)
        .toolbar {
            ToolbarItem(placement: .principal) {
                HStack {
                    Image(systemName: "sun.min.fill")
                    Text("Title").font(.headline)
                }
            }
        }
}
like image 29
Eduard Streltsov Avatar answered Oct 19 '22 08:10

Eduard Streltsov


You can't change the text format in title. But here is a work around, it will work as requested (without large gap):

HStack{
    Text("Todo Lists")
}
.multilineTextAlignment(.center)
.font(.largeTitle)
.padding(.bottom, -15.0)
NavigationView{
    List{
        ForEach(instrNewOld) { instrIdx in
            SourceCodeView(cat: instrIdx)
        }
    }
    .navigationBarTitle(Text("no text"), displayMode: .automatic)
    .navigationBarHidden(true)
}
like image 2
Enrico Avatar answered Oct 19 '22 07:10

Enrico