UIViewRepresentable 自身相对于其中的 UIKit 控件的大小如何? [英] How does UIViewRepresentable size itself in relation to the UIKit control inside it?

查看:27
本文介绍了UIViewRepresentable 自身相对于其中的 UIKit 控件的大小如何?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很困惑,无法找到有关如何包装 UIKit 组件并正确调整其大小的文档.这是最简单的例子,包装一个 UILabel:

I'm totally perplexed and unable find documentation on how to wrap a UIKit component and have it be sized correctly. Here's the simplest example, wrapping a UILabel:

public struct SwiftUIText: UIViewRepresentable {
    @Binding public var text: String

    public init(text: Binding<String>) {
        self._text = text
    }

    public func makeUIView(context: Context) -> UILabel {
        UILabel(frame: .zero)
    }

    public func updateUIView(_ textField: UILabel, context: Context) {
        textField.text = text
        textField.textColor = .white
        textField.backgroundColor = .black
    }
}

没什么特别的,只是一个 UILabel 现在可以用于 SwiftUI.我会将其包含在视图中:

Nothing special, just a UILabel now ready for SwiftUI. I'll include it in a view:

    var body: some View {
        VStack {
            Text("Hello, World!!! \(text)")
                .font(.caption1Emphasized)

            SwiftUIText(text: $helperText)
        }
        .background(Color.green)
    }

结果就是这个画面.请注意顶部的 Text 如何只占用它需要的大小,但 SwiftUIText 占用了所有垂直空间.在代码的其他迭代中,我看到它缩小了,不再只占用少量的水平空间.

The result is this screen. Notice how the Text at the top takes up just the size it needs, but SwiftUIText takes up all that vertical space. In other iterations of the code, I've seen it shrunken down and not taking up just a small amount of horizontal space.

有人可以解释我如何指定我的组件应该 (A) 用完所有可用的宽度和 (B) 只需要它需要的高度?

Can someone explain how I can specify that my component should (A) use up all the width available to it and (B) only the height it needs?

推荐答案

最简单快捷的解决方法:

Most simple and quick fix:

        SwiftUIText(text: $helperText).fixedSize()

更新:

        SwiftUIText(text: $helperText)
            .fixedSize(horizontal: false, vertical: true)

这篇关于UIViewRepresentable 自身相对于其中的 UIKit 控件的大小如何?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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