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\$

bumped to the homepage by Community 2 days ago

This question has answers that may be good or bad; the system has marked it active so that they can be reviewed.

0
\$\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\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.