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)
}
}
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 does not respect the size of the UIView and just give it maximum possible width/height.
Runnable example: SizedUIViewRepresentableView
There is a similiar question asked for a UITextView here: Update UIViewRepresentable size from UIKit in SwiftUI
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…