swiftuitext-alignment

How do I get a SwiftUI Text view to lay out my text top-left aligned?


I figured out how to make a text view's contents scroll by enclosing it in a ScrollView.

However, when there is not enough content to fill a line, it ignores my request to use leading alignment and center-aligns it both horizontally and vertically.

ScrollView() {
    Text(userSettings.wordList)
        .lineLimit(nil)
        .multilineTextAlignment(.leading)
        .padding(.all, 2)
        .frame(minWidth: geometry.size.width - 30, minHeight: 200)
        .border(.blue)
}
.contentMargins(2, for: .scrollContent)
.border(.gray)

That code (with a blue border around the Text view, so you can see how it lands inside the ScrollView) looks like this with 2 words in the Text view:

enter image description here

I want the text to be left (er, leading) aligned horizontally, and top-aligned vertically. How do I do that?


Solution

  • Right now, your frame has no alignment and is defaulting to center. You can fix this by adding an explicit alignment:

    .frame(minWidth: geometry.size.width - 30, minHeight: 200, alignment: .topLeading)