Home > OS >  Wrapping view inside NavigationLink overrides text alignment of Text in view to centered
Wrapping view inside NavigationLink overrides text alignment of Text in view to centered

Time:04-20

I created a custom menu consisting of Views in a Scrollview.

struct MenuInformationDetailView: View {
var title: String = "title"
var subTitle: String = "subTitle"
var imageName: String = "exclamationmark.circle.fill"

var body: some View {
    HStack(alignment: .center) {
        Image(systemName: imageName)
            .font(.largeTitle)
            .foregroundColor(.white)
            .padding()
            .accessibility(hidden: true)

        VStack(alignment: .leading) {
            Text(title)
                .font(.headline)
                .foregroundColor(.white)
                .accessibility(addTraits: .isHeader)

            Text(subTitle)
                .font(.body)
                .foregroundColor(.white)
                .opacity(0.8)
                .fixedSize(horizontal: false, vertical: true)
        }
    }
    .padding(.top)
}
}

Then I wrap the view in a NavigationLink to go to the desired destination:

NavigationLink(destination: PanicDiaryEducationView()) {
        InformationDetailView(title: "Changing behaviour", subTitle: "How to use the behavioural experiments feature", imageName: "questionmark.circle.fill")
                       }

For some reason, doing this causes the Subtitle text (and probably title) to be Centered rather than the default leading alignment. using .frame(alignment : .topLeading) doesn't change it.

When not wrapped in the NavigationLink It formats correctly.

How can I stop it from centering the Text?

Centered Correct

CodePudding user response:

This is something about default multi-line text alignment. As with many default in SwiftUI it is very often not obvious. So it is better to make it explicit. So here is a fix:

Text(subTitle)
    .font(.body)
    .multilineTextAlignment(.leading)   // << here !!
  • Related