Home > front end >  how to change rectangle height based on the overlay text content size
how to change rectangle height based on the overlay text content size

Time:02-06

I want to display some text as an overlay of a rounded rectangle and change the height of the rectangle dynamically as the text grows. I have tried the method below but the textHeight variable did not seem to get updated

struct TestView: View {
    @State var textHeight: CGFloat = 0
    var body: some View {
        RoundedRectangle(cornerRadius: 10)
            .foregroundColor(.bgGreen)
            .frame(width: 300, height: textHeight)
            .overlay(
                Text("This is a big paragraph. This is a big paragraph. This is a big paragraph. This is a big paragraph. This is a big paragraph. This is a big paragraph. This is a big paragraph. This is a big paragraph. This is a big paragraph. This is a big paragraph. This is a big paragraph.This is a big paragraph. This is a big paragraph. This is a big paragraph. This is a big paragraph. This is a big paragraph. This is a big paragraph. This is a big paragraph. This is a big paragraph. This is a big paragraph. This is a big paragraph. This is a big paragraph.")
                    .overlay(
                        GeometryReader { proxy in
                            Color
                                .clear
                                .preference(key: ContentLengthPreference.self,
                                            value: proxy.size.height)
                        }
                    )
            )
            .onPreferenceChange(ContentLengthPreference.self) { value in
                DispatchQueue.main.async {
                    self.textHeight = value
                }
            }
    }
}

struct ContentLengthPreference: PreferenceKey {
    static var defaultValue: CGFloat { 0 }
    static func reduce(value: inout CGFloat, nextValue: () -> CGFloat) {
        value = nextValue()
    }
}

CodePudding user response:

As Asperi wrote it would propably be easier to put a Rectangle in the Background:

Text("this is a text")
    .padding()
    .background(
        RoundedRectangle(cornerRadius: 10)
            .foregroundColor(.green)
    )

I tried it out and it seems to work fine.

  •  Tags:  
  • Related