gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 21:58:24 24 4
gpt4 key购买 nike

我很困惑,无法找到有关如何包装 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。我会将它包含在一个 View 中:
    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

最佳答案

最简单快速的修复:

demo

        SwiftUIText(text: $helperText).fixedSize()

更新:

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

关于ios - UIViewRepresentable 自身相对于其中的 UIKit 控件的大小如何?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60855987/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com