在SwiftUI中,我们可以使用RoundedRectangle
来绘制矩形,并将其样式设置为虚线。
要创建一个具有虚线边框的RoundedRectangle
,您可以使用以下代码:
struct DashedRoundedRectangle: View {
var body: some View {
RoundedRectangle(cornerRadius: 10)
.stroke(style: StrokeStyle(lineWidth: 2, dash: [5]))
}
}
在上述代码中,我们首先创建了一个RoundedRectangle
,并将其cornerRadius
设置为10。然后,我们使用.stroke()
方法为矩形添加边框样式。
在.stroke()
中,我们通过StrokeStyle
结构体来定制边框的样式。在这里,我们将lineWidth
设置为2,以定义边框的宽度,并使用dash
数组来定义虚线的模式。这里的[5]
表示虚线中实线和空白之间的间距为5。
最后,只需将DashedRoundedRectangle
视图添加到父视图中即可看到具有虚线边框的圆角矩形。
struct ContentView: View {
var body: some View {
VStack {
DashedRoundedRectangle()
.frame(width: 200, height: 100)
}
}
}
请记住,在iOS 13及更高版本上可用的SwiftUI版本中,RoundedRectangle
的虚线样式可能仅在模拟器或设备运行时才能看到效果。如果在预览中无法看到虚线效果,请尝试在模拟器或设备上运行您的应用程序。