简体   繁体   English

UIViewRepresentable 自动调整大小 - 将 UIKit UIView 大小传递给 SwiftUI

[英]UIViewRepresentable automatic size - Passing UIKit UIView size to SwiftUI

Assume you have a UIKit view that wants to decide about its own size (via intrinsicContentSize or layout constraints, the size might change).假设您有一个 UIKit 视图,它想要决定自己的大小(通过 intrinsicContentSize 或布局约束,大小可能会改变)。 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?您如何将其包装为 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 does not respect the size of the UIView and just give it maximum possible width/height. SwiftUI 不尊重 UIView 的大小,只是给它最大可能的宽度/高度。

Runnable example: SizedUIViewRepresentableView可运行示例: SizedUIViewRepresentableView

There is a similiar question asked for a UITextView here: Update UIViewRepresentable size from UIKit in SwiftUI这里有一个关于 UITextView 的类似问题: Update UIViewRepresentable size from UIKit in SwiftUI

The solution is to set explicitly compression/hugging priority for represented UIView解决方案是为表示的UIView显式设置压缩/拥抱优先级

Tested with Xcode 11.4 / iOS 13.4使用 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM