Wak
Wak

Reputation: 878

SwiftUI Text alignment with maxWidth not working

I have the following code:

struct ContentView: View {
    var body: some View {
        Text("Test")
            .foregroundColor(.white)
            .font(.subheadline)
            .frame(maxWidth: .infinity)
            .alignmentGuide(.leading) { d in d[.leading] }
            .background(Color(.blue))
    }
}

But as you can see on the image bellow, it does not left align the text. Does anyone knows why this is happening? Maybe because i'm using maxWidth the alignmentGuide thinks it's already left aligned?

result

Upvotes: 16

Views: 8997

Answers (1)

Asperi
Asperi

Reputation: 257711

Because alignmentGuide has effect in container with other subviews. In this case you need to align Text within own frame.

Here is solution

demo

Text("Test")
    .foregroundColor(.white)
    .font(.subheadline)
    .frame(maxWidth: .infinity, alignment: .leading)   // << here !!
    .background(Color(.blue))

Upvotes: 46

Related Questions