swiftui - My implementation of a RichText view that has a show more button does not detect when it is truncated - Stack Overflow

admin2025-04-25  2

I am sort of following the lead of this solution which works for Text objects but am trying to do this for RichText. Currently using this RichText SPM library which seems to just use a WebView underneath.

Right off the bat I had issues with a RichText view placing itself differently when given a maxHeight so I had to sort of improvise to the way the code is now. In my head there is no reason this shouldn't work. In practice while this truncates the height of the RichText view it does not seem to recognize when its been cut off and show a "show more" button to expand it.

private struct EstimateSummaryView: View {
    var richText: String
    let limit: CGFloat = 100

    @State var showMore: Bool = false

    @State var truncated: Bool = false

    var body: some View {
        if showMore {
            richTextView
        } else {
            Color.gray
                .frame(minHeight: limit)
                .frame(maxHeight: showMore ? .infinity : limit)
                .overlay(alignment: Alignment(horizontal: .leading, vertical: .top)) {
                    richTextView
                        .background {
                            GeometryReader { fullTextGeo in
                                Color.clear.onAppear {
                                    truncated = fullTextGeo.size.height > limit
                                }
                            }
                        }
                }
                .clipped()

            if truncated {
                Button(action: {
                    withAnimation {
                        showMore = true
                    }
                }, label: {
                    Text("Show more")
                })
            }
        }
    }

    var richTextView: some View {
        RichText(html: richText)
            .fontType(.system)
            .foregroundColor(light: Color.gray, dark: Color.gray)
            .lineHeight(120)
            .colorScheme(.light)
    }
}
转载请注明原文地址:http://anycun.com/QandA/1745531683a90844.html