简体   繁体   中英

How do I wrap truncated text in a SwiftUI Text with quotes?

I want to achieve exactly the same effect as specified by this question , except in SwiftUI. That is, I want a Text object set to .lineLimit(3).truncationMode(.tail) that will render the text, including the trailing ellipsis, inside proper typographical quotation marks, like so: “It was the best of times, it was...”

The best solution for the problem in UIKit won't transfer over to SwiftUI in the obvious way:

Text("“\(transcript)").lineLimit(3).truncationMode(.tail) + Text("”") // error

Xcode complains that "Cannot convert value of type 'some View' to expected argument type 'Text'", as the type of the return of lineLimit(_:) and truncationMode(_:) aren't Text and therefore concatenation with + isn't allowed. I couldn't get any combination of casts or wrapping various parts in @ViewBuilder s to work, which makes sense. They're different types.

Is there any way of doing this without basically re-implementing .lineLimit(_:) myself?

The best way we found so far is to kind of define the problem away, which maybe turns out to be a better typographic solution anyway:

HStack(spacing: 0) {
    VStack {
        Text("“")
        Spacer()
    }
    HStack {
        Text("Very long text to be truncated goes here")
            .lineLimit(2)
    }
    VStack {
        Spacer()
        Text("”")
    }
}

This puts the quote characters to the left and right of the text, which is kind of what you want for a "pull quote" anyway.

上面的 SwiftUI 片段,用于演示引号如何位于截断文本正文的左侧和右侧

You can put everything in a HStack and set alignment and spacing for it and then divide the text so that the closing quote is in a separate Text component

HStack(alignment: .lastTextBaseline, spacing: 0) {
    Text("“\(longText)")
        .truncationMode(.tail)
    Text("”")
}
.lineLimit(2)

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