【问题标题】:How does UIViewRepresentable size itself in relation to the UIKit control inside it?UIViewRepresentable 相对于其中的 UIKit 控件如何调整自身的大小?
【发布时间】:2020-03-25 19:23:27
【问题描述】:

我完全感到困惑,无法找到有关如何包装 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
    }
}

没有什么特别的,只是一个现在为 SwiftUI 准备好的 UILabel。我会将它包含在一个视图中:

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

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

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

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

【问题讨论】:

    标签: ios swift swiftui


    【解决方案1】:

    最简单快速的修复:

            SwiftUIText(text: $helperText).fixedSize()
    

    更新:

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

    【讨论】:

    • 哦,哇!这帮了很多忙!谢谢!另一个快速的问题,有没有办法强制你的组件占据它所在的 Stack 的整个宽度?
    猜你喜欢
    • 1970-01-01
    • 2023-04-06
    • 1970-01-01
    • 2023-04-10
    • 2019-12-05
    • 2011-02-02
    • 2020-06-29
    • 1970-01-01
    • 2012-09-03
    相关资源
    最近更新 更多