Search code examples
swiftui

SwiftUI - How to Preallocating space for multiple lines of text


In my view I have some text that changes. So ...

Text("Text that changes and may wrap")

Because there are multiple of these text on screen as well as other SwiftUI components I want the text components to occupy the space required for two lines of text regards of how much text they contain. This is so when the text changes the UI doesn't jink around due to the text resizing.

So I'd like these two to occupy the same space:

+-------------------------------+
| A short piece of text         |
|                               |
+-------------------------------+
+-------------------------------+
| A longer piece of text that   |
| wraps around.                 |
+-------------------------------+

However I'm having trouble figuring out how to do this as there doesn't appear to be any property of a Text component that specifies how many lines to display.

anyone know how to specify the height of a text component based on the lines? Some sort of fixed size based on the font and line spacing perhaps?


Solution

  • For anyone whose interested, here's what I ended up doing:

    ZStack {
    
        // This creates the vertical space of two lines so the
        // actual text doesn't change size when it wraps to two lines.
        Text("\n")
            .foregroundColor(.clear)
    
        Text(variableText)
            .frame(maxWidth: .infinity)
            .multilineTextAlignment(.trailing)
            .lineLimit(2)
    }