[英]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.