swiftui

Text not wrapping in HStack when there's a fixed-width view beside it


I have a SwiftUI layout where a Text view is placed in an HStack alongside a fixed-width colored rectangle. The text doesn't wrap to multiple lines even when it's clearly too long to fit in a single line. enter image description here Here's my code:

struct LeWenView: View {
    var body: some View {
        List {
            VStack {
                HStack {
                    VStack {
                        Text("1234567890123456789012345678901234567890")
                        Text("")
                    }
                    Color.blue.frame(width: 100, height: 72)
                        .padding(EdgeInsets(top: 16, leading: 12, bottom: 0, trailing: 0))
                }
                Spacer().frame(height: 8)
            }
            .background(Color.red)
            .cornerRadius(8)
        }
        .background(Color.blue)
    }
}

But if I remove the outside List , the wrapping will working again.

What's the exact problem here?


Solution

  • The List may be basing the layout on the ideal size of its contents. The ideal size of Text is when the text is on one line, so this may be why it subsequently gets truncated.

    Try adding .fixedSize(horizontal: false, vertical: true) to the VStack to prevent it from truncating:

    VStack {
        Text("1234567890123456789012345678901234567890")
        Text("")
    }
    .fixedSize(horizontal: false, vertical: true) // 👈 here
    

    Screenshot