iosswiftswiftuiswiftui-text

How to handle text wrapping and alignment / padding with consecutive Text Views in SwiftUI?


When putting Text() views that have enough text to cause it to wrap, one after the other, they don't have the same alignment / padding unless they have a similar word structure.

I would like to both have a solution to this problem that allows for every Text view to have the same alignment and padding, as well as understand the SwiftUI Magic that I am apparently trying to fight.

I believe it has to do with the default "auto centering" alignment behavior of swiftUI but not sure why sentences of similar length don't appear with the same alignment / padding. And when I have tried to apply a group to the text views and apply collective padding or multiLineAlignment etc it doesn't seem to change the output.

struct TutorialView: View {
    var body: some View {
        
        VStack {
            Text("About This App.")
                .padding([.top, .bottom] , 20)
                .font(.system(size: 30))
            

            Text("This example text is meant to be long enough to wrap because when it is, then the alignment aint what we thought it would be...")
            
            Text("This is meant to wrap and it will look different than the text above. even though it wraps too")
            
            Text("It isn't always clear which will appear to have padding and which will hug the wall")
            
            Text("Literally all of these are differnt...")
                
            Spacer()
            
        }
        
    }
}

Text output example


Solution

  • Approach

    Code

    I have modified your code just to demonstrate the layout

    struct ContentView: View {
        var body: some View {
            VStack {
                Text("About This App.")
                    .padding([.top, .bottom] , 20)
                    .font(.system(size: 30))
                    .background(.orange)
                VStack(alignment: .leading) {
                    Text("This example text is meant to be long enough to wrap because when it is, then the alignment aint what we thought it would be...")
                        .background(.green)
                    Text("This is meant to wrap and it will look different than the text above. even though it wraps too")
                        .background(.blue)
                    Text("It isn't always clear which will appear to have padding and which will hug the wall")
                        .background(.red)
                    Text("Literally all of these are differnt...")
                        .background(.yellow)
                    Spacer()
                }
            }
        }
    }
    

    Text alignment

    Note: