DEV Community

D. Prameswara
D. Prameswara

Posted on • Originally published at swift.my.id on

SwiftUI's Multiline Text Alignment Guide

SwiftUI's Multiline Text Alignment Guide

When using Text views in SwiftUI that consist of multiple words or sentences, by default, the Text view will be displayed with left-aligned text that wraps across several lines. If you want to change this alignment , you can use a specific modifier called multilineTextAlignment.

func multilineTextAlignment(_ alignment: TextAlignment) -> some View
Enter fullscreen mode Exit fullscreen mode

Where the values for TextAlignment can be center, leading, or trailing. Here's an example of how to adjust text alignment in a Text view with multiple lines:

import SwiftUI

struct ContentView: View {
    var body: some View {
        Text("Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nullam vitae elementum lorem, id pharetra metus.")
            .multilineTextAlignment(.center)
            .padding()
    }
}

Enter fullscreen mode Exit fullscreen mode

SwiftUI's Multiline Text Alignment Guide

If you want to limit the maximum number of lines that can be displayed, then you can add the lineLimit modifier as well.

func lineLimit(_ number: Int?) -> some View


import SwiftUI

struct ContentView: View {
    var body: some View {
        Text("Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nullam vitae elementum lorem, id pharetra metus.")
            .multilineTextAlignment(.center)
            .lineLimit(2)
            .padding()
    }
}

Enter fullscreen mode Exit fullscreen mode

SwiftUI's Multiline Text Alignment Guide

By adding the lineLimit, if the number of lines exceeds the limit, the text will automatically be displayed with an ellipsis (...).

Here is an example of implementing the multilineTextAlignment modifier:

SwiftUI's Multiline Text Alignment Guide

That's all for this tips and tricks. Give it a try, and hopefully, this little insight proves to be useful.

[

GitHub - meshwara/SwiftUI-MultilineTextAlignment

Contribute to meshwara/SwiftUI-MultilineTextAlignment development by creating an account on GitHub.

SwiftUI's Multiline Text Alignment GuideGitHubmeshwara

SwiftUI's Multiline Text Alignment Guide
](https://github.com/meshwara/SwiftUI-MultilineTextAlignment?ref=swift.my.id)

Sentry mobile image

App store rankings love fast apps - mobile vitals can help you get there

Slow startup times, UI hangs, and frozen frames frustrate users—but they’re also fixable. Mobile Vitals help you measure and understand these performance issues so you can optimize your app’s speed and responsiveness. Learn how to use them to reduce friction and improve user experience.

Read full post →

Top comments (0)

Sentry mobile image

Improving mobile performance, from slow screens to app start time

Based on our experience working with thousands of mobile developer teams, we developed a mobile monitoring maturity curve.

Read more