Search code examples
swiftuiswiftui-text

Make a text element always "two lines"


I have a vertical stack like this

VStack
  Text(lineA)
    .lineLimit(2)

  Text(lineB)

  Text(lineC)
}

Don't ask me why. My bosses decided that they want the first Text always with two lines, even if the lineA variable has no characters to make the Text grow to two lines.

Is there a way to make the first Text to render if it is two lines and to still show the reticences if there is more than 2 lines?

I can see using a frame to do that, a kind of suicide, fixing the height to a value in points that may vary from device to device.

Is there a less lethal solution?


Solution

  • Following @Asperi brilliant idea, I tested another option that worked better for me:

    var body: some View {
        VStack {
            Text("asdfasfdasfasfasfafddafas\n")
                .lineLimit(2)
                .foregroundColor(.black)
                .frame(maxWidth: .infinity)
    
            Text("lineB")
            Text("lineC")
        }
    }
    

    This will make it 2 lines even if the text is only enough for one and if the text exceeds two lines, the reticences will be added.