How to horizontally align views with navigation bar items in SwiftUI

Viewed 235

How do you get views to align with the navigation bar items? This can be done in a UIKit app via view.layoutMarginsGuide.

Here’s an example:

var body: some View {
    NavigationView {
        VStack {
            Text("Lorem ipsum  nunc fermentum euismod.")
                .background(Color.gray)
                .padding() //FIXME
                .navigationBarTitle("Title")
                .navigationBarItems(leading: Button("Hello"){}, trailing: Button("World"){})
            Spacer()
        }
        .frame(minWidth: 0, maxWidth: .infinity, minHeight: 0, maxHeight: .infinity, alignment: .topLeading) //make it fill the width
    }
    .navigationViewStyle(StackNavigationViewStyle())
}

This gives the following results on iPad 9.7" portrait and iPhone 11 Pro:

iPad screenshot iPhone screenshot

1 Answers

This is not a full answer, and it only addresses a small part of your question, but:


Interestingly, on iPhone, the text actually is aligned if you take kerning into account. This is a good example:

Example

Generated by this body:

var body: some View {
    NavigationView {
        VStack(alignment: .leading) {
            Text("Title.").background(Color.gray).padding(.leading)
            Text("Hello.").background(Color.gray).padding(.leading)
            Text("Lorem ipsum  nunc fermentum euismod.").background(Color.gray).padding(.leading)
        }
        .frame(minWidth: 0, maxWidth: .infinity, minHeight: 0, maxHeight: .infinity, alignment: .topLeading)
        .navigationBarTitle("Title")
        .navigationBarItems(leading: Button("Hello"){}, trailing: Button("World"){})
    }
    .navigationViewStyle(StackNavigationViewStyle())
}

If we zoom in, we can see the kerning in action:

Kerning

It turns out that on iPhone––though apparently not on iPad––the text is actually aligned. Notice that the Hs are aligned and that the Ts are aligned:

Alignment

This doesn't really answer your question because you still experience the issue on iPad. But it does at least narrow it down.

Related