英文:
How to find the frame of a SwiftUI UIViewRepresentable
问题
我正在尝试将UILabel
的自定义子类包装在UIViewRepresentable
中,以便在SwiftUI中使用它。我正在使用.sizeToFit
并打印框架,当它在包装器中时,它看起来正确:
func makeUIView(context: Context) -> CustomUILabel {
let view = CustomUILabel()
view.customProperty = model.customProperty
view.sizeToFit()
print(model.latex, view.frame.size) // 这会打印正确的大小,如何传播?
return view
}
但当我在VStack
中运行这个代码时,它以可能的最大空间绘制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()
}
}
}
是否有一种方法可以将UIView
的大小传播到其父视图,类似于在本地SwiftUI
视图上使用首选项键的方式?
英文:
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?
答案1
得分: 3
这是由于使用了 GeometryReader
。
尝试使用:
customView(model: self.model)
.fixedSize()
英文:
It is due to use of GeometryReader
Try to use
custonView(model:self.model)
.fixedSize()
答案2
得分: 1
当使用 UIViewRepresentable
时,你所描述的贪婪行为是由 contentHuggingPriority
控制的,就像在 UIKit 中一直是的一样。
因此,在你的 makeUIView
函数中,你可以这样做:
// 抵制被拉伸至比本身固有尺寸更大
view.setContentHuggingPriority(.defaultHigh, for: .horizontal)
view.setContentHuggingPriority(.defaultHigh, for: .vertical)
英文:
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)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论