-1

How do I prevent my text from being automatically displayed on two lines, instead of fill out the first line to the end, first. Is this a bug? Any suggestions greatly appreciated.

Expecting solution:

enter image description here

This is what I get:

enter image description here


import SwiftUI

struct ContentView: View {
    var body: some View {
        VStack {
            HStack(spacing: 18) {
                
                VStack {
                    Text("Need to add a complete sentence.")
                        .font(.subheadline)
                        .frame(maxWidth: .infinity, alignment: .leading)
                }
                .frame(minWidth: 0, maxWidth: .infinity)
                .background(Color.green)
                
                VStack {
                    Text("Need to add a complete sentence.")
                        .font(.subheadline)
                }
                .frame(minWidth: 0, maxWidth: .infinity, alignment: .leading)
                .background(Color.gray)
                
            }
            .frame(minWidth: 0, maxWidth: .infinity)
            .background(Color.yellow)
            .padding()
            
        }.edgesIgnoringSafeArea(.all)
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

hightech
  • 3,742
  • 3
  • 25
  • 36
  • Does this answer your question https://stackoverflow.com/a/71698509/12299030? – Asperi Aug 20 '22 at 16:43
  • @Asperi - Thank you. Unfortunately it does not solve my issue. – hightech Aug 20 '22 at 17:12
  • If you mean native Text then yes, because it is Text's feature. – Asperi Aug 20 '22 at 17:28
  • This is just happening because it doesn't want to squeeze "complete" in there. In theory, it IS filling up the entire line before moving to the next line. Try with a shorter word to see. – Stoic Aug 20 '22 at 18:25

1 Answers1

0

This is the expected "Orphaned Words" behavior of iOS.

So I would leave it like this and be happy with the result. But if you really want to prevent this, I'm afraid the only solution in SwiftUI is using UILabel with UIViewRepresentable and setting lineBreakStrategy = []

If you search swift orphaned words, you can learn more details about the topic.

https://medium.com/@pearsontsp/working-with-orphaned-words-in-ios-391a4a928e48


I wouldn't recommend but there is a hacky solution as well. Just put some extra empty spaces into your text. So swift thinks "sentence" word is not an orphan anymore:

Text("Need to add a complete sentence.  ")

Then the result will be:

enter image description here

ibrahimyilmaz
  • 2,317
  • 1
  • 24
  • 28