Xcode报错:Button添加stroke导致报错
Xcode报错:Button添加stroke导致报错

Xcode报错:Button添加stroke导致报错

在Swift中,尝试给Button添加stroke时,Xcode发生报错。

Button(action: {
}, label: {
    VStack {
    }
})
.frame(width: 160,height: 130)
.background {
    Image("StockBackground")
        .resizable()
        .scaledToFill()
        .opacity(color == .light ? 1 : 0.5)
}
.stroke(Color.black, lineWidth: 0.5)    // 报错行

在给Button添加stroke时,提示如下报错:

This enum case is defined on ShapeType, and may not be available in this context

并且,会导致Xcode预览编译超时。

经过查询了解到,.stroke()只能用在符合 Shape 协议的视图(比如 RoundedRectangle()、Circle() 等),现在是把 .stroke(…) 直接加在 Button 上了,这是不被支持的。

具体来讲,就是.stroke()是Shape(形状)专属的修饰符,不适用于普通视图(如Button、VStack)。

解决方案:可以使用.overlay()来添加边框线。

Button(action: {}) {
    VStack {
        // 内容
    }
}
.frame(width: 160, height: 120)
.background(
    Image("StockBackground")
        .resizable()
        .scaledToFill()
)
.overlay(
    RoundedRectangle(cornerRadius: 10)
        .stroke(Color.black, lineWidth: 0.5)
)
.cornerRadius(10)
.clipped() // 可选,让背景和圆角一致裁剪
   

如果您认为这篇文章给您带来了帮助,您可以在此通过支付宝或者微信打赏网站开发者。

欢迎加入我们的 微信交流群QQ交流群,交流更多精彩内容!
微信交流群二维码 QQ交流群二维码

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注