How to have text in shapes in SwiftUI?

Here is what I consider to be a more comprehensive answer. This will work as of Xcode 11.5:

Text(question)
    .fixedSize(horizontal: false, vertical: true)
    .multilineTextAlignment(.center)
    .padding()
    .frame(width: 300, height: 200)
    .background(Rectangle().fill(Color.white).shadow(radius: 3))

Notes:

  • fixedSize() will let the text wrap (since .lineLimit(nil) no longer is working). You can omit it if you simply want one line of text with ellipsis
  • multilineTextAlignment() allows you to center or align the text in any way
  • padding() gives the text more space to breathe within the Rectangle()
  • frame() sets the width and height of the Text() and hence, the Rectangle(), since it is the background of the Text()
  • background() sets the shape of the Text()’s background. I have added a fill color and a drop shadow here as well

The end result of this example is the text looks to appear within a cue card like shape!

Leave a Comment

tech