【问题标题】:UIViewRepresentable automatic size - Passing UIKit UIView size to SwiftUIUIViewRepresentable 自动大小 - 将 UIKit UIView 大小传递给 SwiftUI
【发布时间】:2023-04-06 05:56:01
【问题描述】:

假设你有一个 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

【问题讨论】:

    标签: ios swiftui


    【解决方案1】:

    解决方案是为表示的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) {
        }
    }
    

    【讨论】:

    • 请注意,此策略似乎不适用于 UIStackViews。似乎堆栈总是占据所有可用的区域。
    • makeUIView 中的两个setContentHuggingPriority 替换为view.translatesAutoresizingMaskIntoConstraints = false 对我有用。
    猜你喜欢
    • 2019-12-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多