Search code examples
swiftuitextalignment

How can I align the inside of a Text view?


I have a multiline text field which I would like to appear as:

enter image description here

I’ve tried every combination of padding and frame that I can find on the Internet, and I get something like this:

Text("the cat sat on the mat\nand that is that")
    .multilineTextAlignment(.leading)
    .padding(.horizontal, 12.0)
    .padding(.vertical, 6.0)
    .frame(maxWidth: .infinity, maxHeight: .infinity)
    .border(.black)

Which looks like this:

enter image description here

If the text is longer, it will move over to the left, but I can’t get it there from the beginning.

What’s the technique?


Solution

  • Adding another border helps illustrate what's happening:

    Text("the cat sat on the mat\nand that is that")
       .multilineTextAlignment(.leading)
       .padding(.horizontal, 12.0)
       .padding(.vertical, 6.0)
       .border(Color.green)
       .frame(maxWidth: .infinity, maxHeight: .infinity)
       .border(.black)
    

    enter image description here

    So, you can see that the Text doesn't take up the entire frame. You can add an alignment to the frame so that the Text appears where you intend.

    Text("the cat sat on the mat\nand that is that")
       .multilineTextAlignment(.leading)
       .padding(.horizontal, 12.0)
       .padding(.vertical, 6.0)
       .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .leading) // <-- Here
       .border(.black)
    

    enter image description here