1

I can't seem to grasp how to make sure that my text overlays and fits within the circular image's boundaries. This is what I have so far.

Circle()
    .frame(width: 100, height: 100)
    .overlay(
        Text("Reaaaallllllyyyyyy Looooooongggggg")
            .foregroundColor(Color.red)
            .frame(minWidth: 0, maxWidth: .infinity)
        )

Text overlayed on top of circle

Is there a way in SwiftUI to get this to work? How would I go about achieving this?

Petesta
  • 1,623
  • 3
  • 19
  • 29
  • 2
    I know nothing of SwiftUI but it seems probable that you'd have to use TextKit just as you would with Cocoa, as in this example: https://stackoverflow.com/a/22179416/341994 – matt Apr 09 '21 at 23:49

1 Answers1

2
struct ClippedCircleView: View {
    @State var text: String = "Reaaaallllllyyyyyy Looooooongggggg"
    // Make this any number you are comfortable with
    @State var letterLimit: Int = 12
    var body: some View {
        
        Circle()
            .frame(width: 100, height: 100)
            .overlay(
                Text(text)
                    //Limit to 1 line until your letterLimit
                    .lineLimit(text.count <= letterLimit ? 1 : nil)
                    //Clips it to shape
                    .clipShape(ContainerRelativeShape()).padding()
                    .foregroundColor(Color.red)
                    //This makes super tiny letters so adjust to your use case
                    .minimumScaleFactor(0.1)
                
            )
    }
}
lorem ipsum
  • 21,175
  • 5
  • 24
  • 48
  • This worked for me. With a long string like in the example, would you make the font smaller if the string is above a certain length? That way it fits on one line. – Petesta Apr 10 '21 at 00:21
  • You can, just make the `.linelimit` conditional to the length that you want. See the code. – lorem ipsum Apr 10 '21 at 00:31