How does UIViewRepresentable size itself in relation to the UIKit control inside it?

こ雲淡風輕ζ 提交于 2020-12-06 06:49:06

问题


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
    }
}

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)
    }

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.

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?


回答1:


Most simple and quick fix:

demo

        SwiftUIText(text: $helperText).fixedSize()

Update:

demo2

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


来源:https://stackoverflow.com/questions/60855987/how-does-uiviewrepresentable-size-itself-in-relation-to-the-uikit-control-inside

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!