Search code examples
swiftuirenderingword-wrap

Don't understand SwiftUI Text layout


I want to output some text on all 4 sides of the view. This is my code:

   var body: some View {
        Spacer()
        Text("AA BB CC DD EE FF GG HH")
        Spacer()
        HStack {
            Text("AA BB CC DD EE FF GG HH").rotationEffect(Angle(degrees: -90))
            Spacer()
            Text("AA BB CC DD EE FF GG HH").rotationEffect(Angle(degrees: 90))
        }.frame(height: 200)
        Spacer()
        Text("AA BB CC DD EE FF GG HH")
        Spacer()
    }
}

and this is the output:
enter image description here

Questions:

  • Why is the text left wrapped, but the same text right not? And how can I avoid wrapping?
  • Why has the text left a different margin than the text right? And how can I make them equal?

Solution

  • I believe part of the problem is that you're not forcing both to be centered, also one is drawn, in it's layout priority before the other. So If you set their frame widths, to their maximum, each would take 1/2 the view. Notice the rotationEffect doesn't actually adjust the frame rotation.

    enter image description here

    Getting your frames to constantly match is the only "True" way to resolve this issue, or to use other formatting tricks such as .minimumFontScale(..) or even .lineLimit(..).

    Example

        VStack {
            Spacer()
            Text("AA BB CC DD EE FF GG HH")
                .frame(maxWidth: .infinity)
            Spacer()
            HStack {
                Text("AA BB CC DD EE FF GG HH").rotationEffect(Angle(degrees: -90))
                    .frame(maxWidth: .infinity)
                Spacer()
                Text("AA BB CC DD EE FF GG HH").rotationEffect(Angle(degrees: 90))
                    .frame(maxWidth: .infinity)
            }.frame(height: 200)
            Spacer()
            Text("AA BB CC DD EE FF GG HH")
                .frame(maxWidth: .infinity)
            Spacer()
        }
        .multilineTextAlignment(.center)
    

    In this example I can get an expected output for various dynamic types like so.

    enter image description here