6

I'm trying to fill the capsuled strokeBorder but unfortunately it's filling the rectangle. See picture below:

enter image description here

Any ideas how I can make it fill till the strokeborder only? I'm wanting to use the field as search box which is why I want to use the textfield in it.

Here's my code:

struct ContentView: View {
    
    var body: some View {
        
        HStack{
            TextField("Search", text: .constant(""))
        }
        .padding()
        .frame(maxWidth:300)
        .background(
            Capsule()
                .strokeBorder(Color.black,lineWidth: 0.8)
                .background(Color.blue)
                .clipped()
        )
    }
}

Many Thanks!

SwiftUIRookie
  • 591
  • 7
  • 16
  • Does this answer your question https://stackoverflow.com/a/65202353/12299030? Or this one https://stackoverflow.com/a/60574108/12299030? Or https://stackoverflow.com/a/60375025/12299030? ... try to search and find more )) – Asperi Dec 05 '21 at 20:10

2 Answers2

11

I think this is what you are after.

struct ContentView: View {

var body: some View {
    
    HStack{
        TextField("Search", text: .constant(""))
    }
    .padding()
    .frame(maxWidth:300)
    .background(
        Capsule()
            .strokeBorder(Color.black,lineWidth: 0.8)
            .background(Color.blue)
            .clipped()
    )
    .clipShape(Capsule())
    }
}

Xcode preview of HStack with capsule border

Tim Sonner
  • 146
  • 1
  • 6
  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Dec 06 '21 at 04:55
  • Great answer. Small thing, I noticed removing the `.clipped()` from inside `background` didn't make a difference. – Patrick May 19 '22 at 17:54
1

Use the .fill modifier, but since you can't edit stroke and fill simultaneously set the stroke on the Capsule then set its background as a filled Capsule:

struct ContentView: View {
    var body: some View {
        HStack {
            TextField("Search", text: .constant(""))
        }
        .padding()
        .frame(maxWidth: 300)
        .background {
            Capsule(style: .circular)
                .strokeBorder(Color.black, lineWidth: 0.8)
                .background(Capsule().fill(.blue))
        }
    }
}

If you do this a lot, consider adding an extension to Shape to make it seamless:

extension Shape {
func fill<Fill: ShapeStyle, Stroke: ShapeStyle>(_ fillStyle: Fill, strokeBorder strokeStyle: Stroke, lineWidth: Double = 1) -> some View {
    self
        .stroke(strokeStyle, lineWidth: lineWidth)
        .background(self.fill(fillStyle))
    }
}
Bryan Bryce
  • 1,310
  • 1
  • 16
  • 29