Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to have text in shapes in SwiftUI?

Tags:

swift5

swiftui

I want to add text (eg. Hi) in a shape (eg. Square) in SwiftUI and make them act as a single object.

It looks like there's no direct way to add text in shape in SwiftUI.

like image 672
AtharvSalokhe Avatar asked Dec 03 '19 13:12

AtharvSalokhe


People also ask

How do you make a rounded rectangle in SwiftUI?

Any SwiftUI view can have its corners rounded using the cornerRadius() modifier. This takes a simple value in points that controls how pronounced the rounding should be.


2 Answers

Here is, IMO, most simple approach:

Generic schema

Text(_any_of_text_)
    .background(_any_of_Shape)

eg:

Text("Hello, World!")
    .background(Rectangle().stroke())

Text("Hello, World!")
    .background(RoundedRectangle(cornerRadius: 4).stroke())
like image 180
Asperi Avatar answered Oct 28 '22 17:10

Asperi


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!

like image 33
Gene Loparco Avatar answered Oct 28 '22 17:10

Gene Loparco