简体   繁体   English

如何找到 SwiftUI UIViewRepresentable 的框架

[英]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.我试图在UIViewRepresentable包装UILabel的自定义子类,以便在UIViewRepresentable中使用它。 I'm using .sizeToFit and printing the frame, and it looks right while it's in the wrapper:我正在使用.sizeToFit并打印框架,它在包装器中时看起来.sizeToFit

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.但是当我在VStack运行它时,它UIViewRepresentable以尽可能大的空间绘制UIViewRepresentable

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?有没有办法将UIView的大小传播到其父级,类似于在原生SwiftUI视图上使用首选项键的方式?

It is due to use of GeometryReader这是由于使用GeometryReader

Try to use尝试使用

custonView(model:self.model)
    .fixedSize()

When using UIViewRepresentable , the greediness you describe is controlled using the contentHuggingPriority , just like it always was in UIKit.使用UIViewRepresentable ,您描述的贪婪是使用contentHuggingPriority控制的,就像在 UIKit 中一样。

So in your makeUIView function, you can do this:所以在你的makeUIView函数中,你可以这样做:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM