How to know if text reaches the line limit in SwiftUI?

2024-11-12
#code-snippet #swiftui
// to see if text reaches the limit
@State private var isTruncated = false

Text("text content")
        .font(.body)
        .lineLimit(3) // your own limit
        .background(
            ViewThatFits(in: .vertical) { // returns first child that fits inside line-limited text
                Text("text content") // text fits in less than or equal to line limit
                    .hidden()
                Color.clear // text doesn't fit
                    .onAppear { isTruncated = true }
            }
)