Home > Mobile >  One line each word in a single Text SwiftUI?
One line each word in a single Text SwiftUI?

Time:07-10

This is what I have:

enter image description here

First square is correct cause the word is longer than the frame so multiline works good...in the last square I'd like to have JUDO MIX like BASKETBALL MIX, on 2 lines, but I don't know what to do because Text is in a ForEach and I can't edit Text frame, otherwise BASKETBALL and other words will be truncated. Any suggestions on how to achieve 1 line each word?

This is my code:

ForEach(0 ..< array.count, id: \.self) { index in
    Image(array[index].val)
        .customReflection()
    VStack {
    Text(array[index].category)
         .font(.title)
         .fontWeight(.bold)
         .multilineTextAlignment(.center)
         .frame(width: 181)
    }
}

CodePudding user response:

Try changing your Text to this:

VStack {
    ForEach(array[index].category.components(separatedBy: " "), id: \.self) { word in
        Text(word)
    }
}

I can't test that solution out at time of writing this, but that should work. It just separates the string by words and puts each on its own line.

Also, instead of .multilineTextAlignment(), just set the alignment of the VStack


Another solution would be to switch out the spaces (" ") in the string with "\n" to make a new line after each word. That would be:

Text(array[index].category.components(separatedBy: " ").joined(separator: "\n"))
  • Related