简体   繁体   中英

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM