简体   繁体   中英

One line each word in a single Text SwiftUI?

This is what I have:

在此处输入图像描述

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM