簡體   English   中英

UIViewRepresentable 自動調整大小 - 將 UIKit UIView 大小傳遞給 SwiftUI

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM