Home > database >  Controlling Text view layout with SwiftUI
Controlling Text view layout with SwiftUI

Time:12-02

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?

CodePudding user response:

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)

CodePudding user response:

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]
  • Related