Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

ios - 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). 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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The solution is to set explicitly compression/hugging priority for represented UIView

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...