![](/img/trans.png)
[英]SwiftUI view like UIKit UIView, How to change the size of the image
[英]UIViewRepresentable automatic size - Passing UIKit UIView size to SwiftUI
假设您有一个 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
解决方案是为表示的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) {
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.