在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() // 可选,让背景和圆角一致裁剪
