假设您有一个UIKit视图,该视图想要确定其自身大小(通过internalContentSize或布局约束,该大小可能会更改)。例如:
/// 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?
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的大小,只是为其提供最大可能的宽度/高度。
可运行的示例:SizedUIViewRepresentableView
这里有一个类似的问题要求提供UITextView:Update UIViewRepresentable size from UIKit in SwiftUI
答案 0 :(得分:7)
解决方案是为表示的UIView
通过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) {
}
}