简体   繁体   English

如何让我的 SwiftUI UIViewRepresentable 在预览中尊重内部内容大小?

[英]How do I make my SwiftUI UIViewRepresentable respect intrinsicContentSize in previews?

When I create a view in SwiftUI and render it in an Xcode preview, using PreviewLayout.sizeThatFits , the preview adjusts its size according to its content.当我在 SwiftUI 中创建一个视图并在 Xcode 预览中呈现它时,使用PreviewLayout.sizeThatFits ,预览会根据其内容调整其大小。 When I import a UIKIt view using UIViewRepresentable , it appears with a full device-size frame.当我使用UIViewRepresentable导入 UIKIt 视图时,它会显示一个完整的设备大小的框架。

Is there a way to make SwiftUI respect the intrinsicContentSize of UIView subclasses?有没有办法让 SwiftUI 尊重UIView子类的intrinsicContentSize内容大小?

struct Label: UIViewRepresentable {

    func makeUIView(context: UIViewRepresentableContext<Label>) -> UILabel {
        return UILabel()
    }

    func updateUIView(_ uiView: UILabel, context: UIViewRepresentableContext<Label>) {
        uiView.text = "Some text"
    }
}

#if DEBUG
struct Label_Previews: PreviewProvider {
    static var previews: some View {
        Group {
            Label().previewLayout(.sizeThatFits)
        }
    }
}
#endif

Add the following to your updateUIView function:将以下内容添加到您的 updateUIView 函数中:

uiView.setContentHuggingPriority(.defaultHigh, for: .vertical)
uiView.setContentHuggingPriority(.defaultHigh, for: .horizontal)

You can also limit the UIViewRepresentable size from the SwiftUI side .您还可以从SwiftUI 端限制UIViewRepresentable大小。

For this you can use fixedSize :为此,您可以使用fixedSize

struct Label_Previews: PreviewProvider {
    static var previews: some View {
        Label()
            .fixedSize()
            .previewLayout(.sizeThatFits)
    }
}

You can also fix the view size in one dimension only:您还可以仅在一维中修复视图大小:

.fixedSize(horizontal: false, vertical: true)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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