SwiftUI - 将胶囊形状填充到描边边缘

6

我试着填充包含的strokeBorder,但不幸的是它填充了矩形。如下图所示:

enter image description here

有什么办法可以让它仅填充到 strokeborder?我想将该字段用作搜索框,这就是为什么我想在其中使用textfield的原因。

以下是我的代码:

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()
        )
    }
}

非常感谢!

这个回答解决了你的问题吗 https://dev59.com/MFEG5IYBdhLWcg3wffX4#65202353?还是这个 https://stackoverflow.com/a/60574108/12299030?或者是这个 https://dev59.com/6VIH5IYBdhLWcg3wQLbr#60375025?...试着搜索并找到更多)) - Asperi
2个回答

11

我想这就是您需要的内容。

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())
    }
}

HStack带胶囊边框的Xcode预览


你的回答可以通过提供更多支持信息来改进。请编辑以添加进一步的细节,例如引用或文档,以便他人可以确认你的答案是正确的。您可以在帮助中心找到有关如何编写良好答案的更多信息。 - Community
很好的回答。小事情,我注意到从background中删除.clipped()没有任何影响。 - Patrick

1
使用.fill修饰符,但由于无法同时编辑描边和填充,因此在Capsule上设置描边,然后将其背景设置为填充的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))
        }
    }
}

如果您经常这样做,请考虑添加一个扩展到Shape,使其更加无缝:
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))
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接