UIViewRepresentable自动大小-将UIKit UIView大小传递给SwiftUI [英] UIViewRepresentable automatic size - Passing UIKit UIView size to SwiftUI
问题描述
假设您有一个UIKit视图,该视图想要确定其自身大小(通过internalContentSize或布局约束,该大小可能会更改).例如:
Assume you have a UIKit view that wants to decide about its own size (via intrinsicContentSize or layout constraints, the size might change). For example:
/// Some UIKit view that wants to have a specific size
class YellowBoxUIKitView : UIView {
init() {
super.init(frame: .zero)
self.backgroundColor = .yellow
}
required init?(coder: NSCoder) {
fatalError("init(coder:) is not supported")
}
override var intrinsicContentSize: CGSize {
return CGSize(width: 100, height: 100)
}
}
如何将其包装为SwiftUI UIViewRepresentable,并使其自动将UIView大小传递给SwiftUI?
How can you wrap this as a SwiftUI UIViewRepresentable and make it pass on the UIView size to SwiftUI automatically?
struct YellowBoxView : UIViewRepresentable {
func makeUIView(context: Context) -> YellowBoxUIKitView {
// TODO: How do you pass the size from UIKit up to SwiftUI?
YellowBoxUIKitView()
}
func updateUIView(_ uiView: YellowBoxUIKitView, context: Context) {
}
}
SwiftUI不尊重UIView的大小,只是为其提供最大可能的宽度/高度.
SwiftUI does not respect the size of the UIView and just give it maximum possible width/height.
可运行示例: SizedUIViewRepresentableable
这里有一个类似的问题要求使用UITextView:从以下位置更新UIViewRepresentable大小SwiftUI中的UIKit
There is a similiar question asked for a UITextView here: Update UIViewRepresentable size from UIKit in SwiftUI
推荐答案
解决方案是为表示的UIView
通过Xcode 11.4/iOS 13.4测试
Tested with Xcode 11.4 / iOS 13.4
struct YellowBoxView : UIViewRepresentable {
func makeUIView(context: Context) -> YellowBoxUIKitView {
let view = YellowBoxUIKitView()
view.setContentHuggingPriority(.required, for: .horizontal) // << here !!
view.setContentHuggingPriority(.required, for: .vertical)
// the same for compression if needed
return view
}
func updateUIView(_ uiView: YellowBoxUIKitView, context: Context) {
}
}
这篇关于UIViewRepresentable自动大小-将UIKit UIView大小传递给SwiftUI的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!