如何让我的 SwiftUI UIViewRepresentable 在预览中尊重内部内容大小? [英] How do I make my SwiftUI UIViewRepresentable respect intrinsicContentSize in previews?

查看:25
本文介绍了如何让我的 SwiftUI UIViewRepresentable 在预览中尊重内部内容大小?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我在 SwiftUI 中创建视图并在 Xcode 预览中呈现它时,使用 PreviewLayout.sizeThatFits,预览会根据其内容调整其大小.当我使用 UIViewRepresentable 导入 UIKIt 视图时,它会显示一个完整的设备尺寸框架.

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. When I import a UIKIt view using UIViewRepresentable, it appears with a full device-size frame.

有没有办法让 SwiftUI 尊重 UIView 子类的 intrinsicContentSize?

Is there a way to make SwiftUI respect the intrinsicContentSize of UIView subclasses?

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

推荐答案

将以下内容添加到您的 updateUIView 函数中:

Add the following to your updateUIView function:

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

这篇关于如何让我的 SwiftUI UIViewRepresentable 在预览中尊重内部内容大小?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆