Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 230
Wak Avatar asked Jul 04 '20 19:07

Wak


People also ask

How do I align text leading in SwiftUI?

To align a text view along the horizontal axis, you need to use . frame() modifier with maxWidth set to . infinity and alignment to the alignment you want. In this example, we align our text to the traling edge with .

How do I move text in SwiftUI?

SwiftUI gives us a number of valuable ways of controlling the way views are aligned, and I want to walk you through each of them so you can see them in action. You can then use offset(x:y:) to move the text around inside that frame.

How do I manually align text?

To align the text left, press Ctrl+L. To align the text right, press Ctrl+R. To center the text, press Ctrl+E.


1 Answers

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))
like image 171
Asperi Avatar answered Oct 12 '22 20:10

Asperi