Eugene
Eugene

Reputation: 4476

How can I make a SwiftUI Text view show two lines regardless of text length?

I'd like to create a Text view that shows two lines of content, and either cut off the remaining text if there is too much, or just display one or two empty lines if the text isn't long enough or is even an empty string. Is this currently possible? Could I create my own Text view that could somehow behave this way?

Upvotes: 5

Views: 2858

Answers (2)

Gregorian.st
Gregorian.st

Reputation: 171

Starting from iOS 16 you can use very simple .lineLimit modifier with reservesSpace parameter:

Text("Some Text").lineLimit(2, reservesSpace: true)

Upvotes: 0

Mojtaba Hosseini
Mojtaba Hosseini

Reputation: 119917

For limiting the lines to only takes two, Use .lineLimit(2) modifier.

For showing empty space if it's empty, you may use .frame() modifier. But if you need to find exact hight of the two line label and apply it, use a placeholder inside a ZStack like this:

ZStack(alignment: .top) {
    Text("\n ").hidden() // Just a place holder to hold required height to show two lines
    Text("Text").lineLimit(2)
}

UPDATE duo to comments

Remember, there are other issues related to other parts of the SwiftUI, For example if you need to use it inside a StackView, you must specify the layoutPriority since it's not required by default.

    NavigationView {
        VStack {
            ZStack(alignment: .top) {
                Text("\n ").lineLimit(2)
                Text("Text").lineLimit(2)
            }.layoutPriority(1000)
            NavigationLink(destination: Text("Destination")) {
                Text("Next")
            }
        }
    }

And if you see SwiftUI likes to trim extra spaces, you can use hidden characters in the placeholder to make it retain. Use this if needed:

(Text("‌‌‎‌‌‎ ")+Text("\n")+Text("‌‌‎ ")).lineLimit(2)

Note that the first and last Text contains an special hidden character.

And yes, you can append Texts together.

Upvotes: 7

Related Questions