James Allardice
James Allardice

Reputation: 165941

Controlling Text view layout with SwiftUI

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?

Upvotes: 0

Views: 623

Answers (2)

Debashish M
Debashish M

Reputation: 323

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]

Upvotes: 0

George
George

Reputation: 30341

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)

Upvotes: 1

Related Questions