UIViewRepresentable自身相对于其中的UIKit控件的大小如何?

时间:2020-03-25 19:23:27

标签: ios swift swiftui

我非常困惑,无法找到有关如何包装UIKit组件并正确调整其大小的文档。这是包装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。我将其包含在视图中:

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

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

结果是此屏幕。请注意,顶部的Text如何仅占据所需的大小,而SwiftUIText却占据了所有垂直空间。在代码的其他迭代中,我看到它缩小了,并且只占用了很少的水平空间。

有人可以解释我如何指定我的组件(A)用尽所有可用的宽度,而(B)仅使用所需的高度吗?

enter image description here

1 个答案:

答案 0 :(得分:3)

最简单快捷的解决方法:

demo

        SwiftUIText(text: $helperText).fixedSize()

更新

demo2

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