|

How to Implement Multiline Text in iOS SwiftUI

In this blog post, we’re focusing on a critical yet sometimes overlooked aspect of developing user interfaces – managing multiline text in SwiftUI. As mobile applications frequently deal with a variety of text-based content, properly handling multiline text is key to maintaining an organized and user-friendly app.

Let’s explore how SwiftUI makes this task straightforward and efficient.

Basics: Allow Text to Wrap

SwiftUI, by default, allows text to wrap and form multiple lines when the content exceeds the line’s width. No extra code is necessary for this functionality:

Text("Hello, SwiftUI! Welcome to the world of declarative user interface design.")

In this case, if the text string cannot fit within a single line in its parent view, SwiftUI automatically wraps the text to the next line, forming a multiline text view.

SwiftUI Text multiline

Limit the Number of Lines

There are instances when you want to limit the number of lines that your text can occupy. SwiftUI provides a handy modifier for this – the .lineLimit() function:

Text("Hello, SwiftUI! Welcome to the world of declarative user interface design.")
    .lineLimit(1)

In this example, the text view will wrap the text over a maximum of one line. If the text is too long to fit within one line, it will be truncated.

limit Text line SwiftUI

Truncation Mode

SwiftUI allows you to specify the behavior of text truncation when the text view’s content exceeds its capacity using the .truncationMode() modifier. It can be set to .head, .middle, or .tail:

Text("Hello, SwiftUI! Welcome to the world of declarative user interface design.")
    .lineLimit(1)
    .truncationMode(.head)

In this snippet, SwiftUI trims the text at the head (the start of the content) when it exceeds the one-line limit.

SwiftUI Text truncation

Being able to manage multiline text in SwiftUI provides you with the power to deliver clear, concise, and user-friendly textual content in your app.

From automatic text wrapping to controlling the number of lines and truncation mode, SwiftUI gives you a host of tools to deliver the best textual presentation.

Similar Posts

Leave a Reply