1

I have the following SwiftUI Text view:

Text("Hello, world. foo bar foobar foo hello world")
  .frame(maxWidth: .infinity, alignment: .leading)
  .padding()
  .background(Color.red)

which renders like this (screenshots from Xcode preview, iPhone 13 Pro):

enter image description here

Adding a single character to the string causes the view to render as follows:

enter image description here

There is clearly space for "hello" on the first line, but the layout engine breaks the lines presumably where it feels is best. Is there any way to control this, to get the text to flow as far as it can on each line, within the constraints of the view?

2
  • I see no issue when I try your code. Commented Dec 1, 2021 at 21:18
  • I think it is not really layout but something like styling, in this case to avoid the only word in next line, ie. if you add, for example, word more at the end then hello goes back to first line. I don't think it can be controlled from SwiftUI. Commented Dec 2, 2021 at 5:45

2 Answers 2

1

You could perhaps use an overlay, with the Text having a fixed size horizontally. This will mean the Text will only take 1 line, and will not wrap to the next line because of the text being too long.

Code:

Text("")
    .frame(maxWidth: .infinity)
    .overlay(alignment: .leading) {
        Text("Hello, world. foo bar foobar foo hello world more words etc etc")
            .fixedSize(horizontal: true, vertical: false)
    }
    .padding()
    .background(Color.red)
Sign up to request clarification or add additional context in comments.

Comments

0

enter image description hereI did not find any problem on my end with your current code, it can take more characters not only single, however, but You can also use this .lineLimit() to control more flexibility:

see my output image:
`Text("Hello, world. foo bar foobar fooooooooo, hello world")
          .frame(maxWidth: .infinity, alignment: .leading)
          .lineLimit(1)
          .padding()
          .background(Color.red)`[![output][1]][1]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.