【发布时间】:2023-04-06 05:56:01
【问题描述】:
假设你有一个 UIKit 视图想要决定它自己的大小(通过 intrinsicContentSize 或布局约束,大小可能会改变)。例如:
/// 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
【问题讨论】: