5
\$\begingroup\$

I am using a set of data points (currently randomly generated), and drawing a line graph inside a box:

struct DrawLine: View {
    var body: some View {
        ZStack {
            Rectangle()
                .stroke(lineWidth: 1.0)
                .fill(Color.purple)
                .frame(width: InstrumentPrices.boxWidth, height: InstrumentPrices.boxHeight, alignment: .center)

            SparkLine()

        }
        .frame(width: 0, height: 0).border(Color.black)
    }
}

struct SparkLine: View {
    @State var myPoints = InstrumentPrices.points

    static let gradientStart = Color(red: 239.0 / 255, green: 120.0 / 255, blue: 221.0 / 255)
    static let gradientEnd = Color(red: 239.0 / 255, green: 172.0 / 255, blue: 20.0 / 255)

    var body: some View {
        ZStack {
            Rectangle()
                .fill(Color.white)
                .onTapGesture {
                    // print ("Tap!")
                    InstrumentPrices.resetPoints()
                    self.myPoints = InstrumentPrices.points
                }

            GeometryReader { geometry in
                Path { path in
                    path.move(to: InstrumentPrices.points[0])

                    self.myPoints.forEach {
                        path.addLine(
                            to: CGPoint(x: $0.x, y: $0.y)
                        )
                    }
                }
                .stroke(lineWidth: 2)
                .fill (LinearGradient (
                    gradient: .init(colors: .init([Self.gradientStart, Self.gradientEnd])),
                    startPoint: .init(x: 0, y: 0),
                    endPoint: .init(x: 1.0, y: 0)
                ))
            }
        }
    }
}

SwiftUI is new enough to me. I'm always looking for better code conventions. Any comments are welcome!

\$\endgroup\$
0

1 Answer 1

2
\$\begingroup\$

The role of your ZStack and border rectangle could be replaced with a .background or .overlay modifier on the Sparkline itself - would allow more flexibility in presentation at the point-of-usage.

\$\endgroup\$

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.