简体   繁体   中英

How to horizontally align views with navigation bar items in SwiftUI

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截图 iPhone 截图

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:

例子

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:

字距调整

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

结盟

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM