本文介绍了UIViewRepresentable 自动大小 - 将 UIKit UIView 大小传递给 SwiftUI的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设你有一个 UIKit 视图想要决定它自己的大小(通过 internalContentSize 或布局约束,大小可能会改变).例如:

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)
    }

}

如何将其包装为 SwiftUI UIViewRepresentable 并使其自动将 UIView 大小传递给 SwiftUI?

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 不考虑 UIView 的大小,只是给它最大可能的宽度/高度.

SwiftUI does not respect the size of the UIView and just give it maximum possible width/height.

可运行示例:SizedUIViewRepresentableView

这里有一个关于 UITextView 的类似问题:Update UIViewRepresentable size fromSwiftUI 中的 UIKit

There is a similiar question asked for a UITextView here: Update UIViewRepresentable size from UIKit in SwiftUI

推荐答案

解决方案是为表示的 UIView

使用 Xcode 11.4/iOS 13.4 测试

Tested with 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) {
    }
}

这篇关于UIViewRepresentable 自动大小 - 将 UIKit UIView 大小传递给 SwiftUI的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-23 08:41