SwiftUI text-alignment

后端 未结 9 1479
逝去的感伤
逝去的感伤 2020-12-29 00:42

Among the many properties of the Text view, I couldn\'t find any related to text alignment. I\'ve seen in a demo that it automatically handles RTL, and when pla

相关标签:
9条回答
  • 2020-12-29 01:07

    From SwiftUI beta 3 forward, you can center a text view with the frame modifier:

    Text("Centered")
        .frame(maxWidth: .infinity, alignment: .center)
    
    0 讨论(0)
  • 2020-12-29 01:10

    You can do this via the modifier .multilineTextAlignment(.center).

    Apple Documentation

    0 讨论(0)
  • 2020-12-29 01:10

    We need to align the Text and not the Stack it's in. So calling multilineTextAlignment(.center) and setting the line limits I can be able to see the texts aligned to center. I don't know why I have to set the line limits, I thought it would expand if you have a large text.

    Text("blahblah")
            .font(.headline)
            .multilineTextAlignment(.center)
            .lineLimit(50)
    
    0 讨论(0)
  • 2020-12-29 01:13

    I've actually run into the problem where I had to align text on a single line. What I've found to work is this:

    Text("some text")
        .frame(alignment: .leading)
    

    If you combine this with the frame width parameter you can get some nice text block formatting for labels and such.

    0 讨论(0)
  • 2020-12-29 01:13

    If you would like to keep constant width for the Text, the ".multilineTextAlignment(.leading)" won't take any effect until there is only one line of text.

    This is the solution that worked for me:

    struct LeftAligned: ViewModifier {
        func body(content: Content) -> some View {
            HStack {
                content
                Spacer()
            }
        }
    }
    
    
    extension View {
        func leftAligned() -> some View {
            return self.modifier(LeftAligned())
        }
    }
    

    Usage:

    Text("Hello").leftAligned().frame(width: 300)
    
    0 讨论(0)
  • 2020-12-29 01:13

    I'd like to use Spacer() view to aligning text block. This example show text at the trailing side:

    HStack{
        Spacer()
        Text("Wishlist")
    }
    
    0 讨论(0)
提交回复
热议问题