The goal is to get a UILabel
integrated via UIViewRepresentable
to size the same way Text
does - use the available width and wrap to multiple lines to fit all the text thus increasing the height of the HStack
it's in, instead of expanding in width infinitely. This is very similar to this question, though the accepted answer does not work for the layout I'm using involving a ScrollView
, VStack
, and HStack
.
struct ContentView: View {
var body: some View {
ScrollView {
VStack {
HStack {
Text("Hello, World")
Text("Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla tempor justo quam, quis suscipit leo sollicitudin vel.")
//LabelView(text: "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla tempor justo quam, quis suscipit leo sollicitudin vel.")
}
HStack {
Text("Hello, World")
Text("Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla tempor justo quam, quis suscipit leo sollicitudin vel.")
}
Spacer()
}
}
}
}
struct LabelView: UIViewRepresentable {
var text: String
func makeUIView(context: UIViewRepresentableContext<LabelView>) -> UILabel {
let label = UILabel()
label.text = text
label.numberOfLines = 0
return label
}
func updateUIView(_ uiView: UILabel, context: UIViewRepresentableContext<LabelView>) {
uiView.text = text
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
Using two Texts in the HStack results in this desired layout:
Using the Text and LabelView results in this undesired layout:
If you wrap the LabelView
in GeometryReader
and pass a width
into LabelView
to set the preferredMaxLayoutWidth
, it's 0.0
for some reason. You can get a width if you move the GeometryReader
outside the ScrollView
, but then it's the scroll view width, not the width SwiftUI is proposing for the LabelView
in the HStack
.
If instead I specify label.setContentCompressionResistancePriority(.defaultLow, for: .horizontal)
it works better, but still doesn't display all the text, it strangely truncates the LabelView
at 3 lines and the second Text
at 2 lines.