SwiftUI - 如何使用 Shape 制作垂直虚线?

Tar*_*riq 4 shapes ios swiftui ios14

struct DottedLine: Shape {
        
    func path(in rect: CGRect) -> Path {
        var path = Path()
        path.move(to: CGPoint(x: 0, y: 0))
        path.addLine(to: CGPoint(x: rect.width, y: 0))
        return path
    }
}

DottedLine()
                .stroke(style: StrokeStyle(lineWidth: 1, dash: [2]))
                .frame(height: 1)
                .foregroundColor(Color.red)
Run Code Online (Sandbox Code Playgroud)

这将创建一条水平虚线。但如何让它垂直呢?如果我将 Divider() 放入 HStack 中,那么它会变成垂直的,但如何用虚线实现相同的效果?

Asp*_*eri 13

对宽度和高度做出DottedLine反应,并根据需要进行配置以代替使用:

演示

struct DottedLine: Shape {
        
    func path(in rect: CGRect) -> Path {
        var path = Path()
        path.move(to: CGPoint(x: 0, y: 0))
        path.addLine(to: CGPoint(x: rect.width, y: rect.height))
        return path
    }
}

struct TestDottedLineView: View {
    var body: some View {
        DottedLine()
            .stroke(style: StrokeStyle(lineWidth: 1, dash: [2]))
            .frame(width: 1, height: 100)
            .foregroundColor(Color.red)
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 将 path.addLine(to: CGPoint(x: rect.width, y: rect.height)) 更改为:path.addLine(to: CGPoint(x: 0, y: rect.height))。否则,该线会稍微向右弯曲。 (3认同)