Home > Net >  Fill text overlay based on Text size on RoundedRectangle
Fill text overlay based on Text size on RoundedRectangle

Time:11-18

Is there a native way to fill in a shape and make the width based on the size of the Text overlay?

Here is the code that I have:

RoundedRectangle(cornerRadius: 25, style: .continuous)
    .stroke(Color.black, lineWidth: 1)
    .frame(width: 100, height: 20, alignment: Alignment.top)
    .overlay(
        Text(item.category)
            .font(.caption.weight(.semibold))
            .foregroundColor(.accentColor)
    )

This created the following rounded rectangle:

enter image description here

Does anyone know how to make the rounded rectangle the size of the Text inside? So basically, instead of passing a width, I want the RoundedRectangle to expand based on the width of the Text automatically, but also leave some padding.

CodePudding user response:

You can try this

Text(item.category)
    .font(.caption.weight(.semibold))
    .foregroundColor(.accentColor)
    .padding(10) // your preference
    .overlay(
        RoundedRectangle(cornerRadius: 25, style: .continuous)
            .stroke(.black, lineWidth: 1)
    )
  • Related