Updated for Xcode 14.2
When SwiftUI’s Text
views wrap across multiple lines, they align to their leading edge by default. If you want to change that, use the multilineTextAlignment()
modifier to specify an alternative, such as .center
, or .trailing
.
For example, this will center several lines of text as they wrap across lines:
Text("This is an extremely long text string that will never fit even the widest of phones without wrapping")
.font(.largeTitle)
.multilineTextAlignment(.center)
.frame(width: 300)
Download this as an Xcode project
You can compare all three text alignments side by side using a picker such as this one:
struct ContentView: View {
let alignments: [TextAlignment] = [.leading, .center, .trailing]
@State private var alignment = TextAlignment.leading
var body: some View {
VStack {
Picker("Text alignment", selection: $alignment) {
ForEach(alignments, id: \.self) { alignment in
Text(String(describing: alignment))
}
}
Text("This is an extremely long text string that will never fit even the widest of phones without wrapping")
.font(.largeTitle)
.multilineTextAlignment(alignment)
.frame(width: 300)
}
}
}
Download this as an Xcode project
SPONSORED From March 20th to 26th, you can join a FREE crash course for mid/senior iOS devs who want to achieve an expert level of technical and practical skills – it’s the fast track to being a complete senior developer!
Sponsor Hacking with Swift and reach the world's largest Swift community!
Link copied to your pasteboard.