Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find the frame of a SwiftUI UIViewRepresentable

I'm trying to wrap a custom subclass of UILabel in UIViewRepresentable to use it in SwiftUI. I'm using .sizeToFit and printing the frame, and it looks right while it's in the wrapper:

func makeUIView(context: Context) -> CustomUILabel {
    let view = CustomUILabel()
    view.customProperty = model.customProperty
    view.sizeToFit()
    print(model.latex,view.frame.size) // this prints the correct size, how to propagate?
    return view
}

but when I run this in a VStack, it draws the UIViewRepresentable with the maximum space possible.

var body: some View {
    GeometryReader{ geometry in
        VStack(spacing: 0){
            Rectangle()
                .fill(Color.red)
                .frame( height: geometry.size.height/2 - 5 + self.draggedOffset.height)
            Rectangle()
                .fill(Color.orange)
                .frame(height: 10)
            custonView(model:self.model)
            Spacer()
    }
}

Is there a way to propagate the size of the UIView to its parent, similar to how you use preference keys on a native SwiftUI view?

like image 441
chartman Avatar asked Nov 23 '25 02:11

chartman


2 Answers

It is due to use of GeometryReader

Try to use

custonView(model:self.model)
    .fixedSize()
like image 56
Asperi Avatar answered Nov 24 '25 21:11

Asperi


When using UIViewRepresentable, the greediness you describe is controlled using the contentHuggingPriority, just like it always was in UIKit.

So in your makeUIView function, you can do this:

// resist being made larger than the intrinsicContentSize
view.setContentHuggingPriority(.defaultHigh, for: .horizontal)
view.setContentHuggingPriority(.defaultHigh, for: .vertical)

Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!