Swift
Completed
-
Section 1: Getting Started
-
Section 2: Core Syntax
-
Section 3: Optionals
-
Section 4: Object-Oriented and Value Types
-
Section 5: Memory Management
-
Section 6: Generics and Error Handling
-
Section 7: Concurrency
-
Section 8: Working with Collections
-
Section 9: Codable and Data Handling
-
Section 10: Protocol-Oriented Programming
-
Section 11: Testing and Tooling
-
Section 12: Practical Projects
-
Section 13: Interview Practice
-
Section 14: More Practice Exercises
-
Section 15: More Standard Library
-
Section 16: Advanced Concurrency
-
Section 17: Foundation Framework Deep Dive
-
Section 18: URLSession and Networking Deep Dive
-
Section 19: Combine Framework
-
Section 20: SwiftUI Fundamentals for Swift Developers
-
Section 21: Server-Side Swift with Vapor
-
Section 22: Swift Package Manager Deep Dive
-
Section 23: Swift Concurrency Deep Dive
-
Section 24: More Language Features
-
Section 25: Error Handling Deep Dive
-
Section 26: Testing Deep Dive
-
Section 27: Data Structures and Algorithms in Swift
-
Section 28: More Practice Exercises
-
Section 29: More Interview Practice
-
Section 30: Swift Macros (Swift 5.9+)
-
Section 31: Property Wrappers Ecosystem
-
Section 32: Swift Interop Deep Dive
-
Section 33: iOS App Architecture Patterns
-
Section 34: Performance and Debugging
-
Section 35: App Distribution and CI/CD
-
Section 36: More Practical Projects
-
Section 37: SwiftData and Persistence
-
Section 38: More Design Patterns
-
Section 39: More Review and Practice
-
Section 40: More Foundation Deep Dive
-
Section 41: Advanced Collections in Swift
-
Section 42: Advanced Generics Practice
-
Section 43: UIKit for Legacy and Hybrid Apps
-
Section 44: watchOS and visionOS Development Basics
-
Section 45: More Networking Patterns
-
Section 46: More Testing Practice
-
Section 47: Accessibility in Swift Apps
-
Section 48: Localization
-
Section 49: More Practical Projects Round 2
-
Section 50: Swift Charts Framework
-
Section 51: More Interview and Algorithm Practice
-
Section 52: Final Practice and Mastery
-
Section 53: Swift Compiler and Build System
-
Section 54: More Concurrency Practice
-
Section 55: App Store Guidelines and Review
-
Section 56: More Design and Architecture
219: Interactive Charts with Gestures
When you first start making your Swift Charts interactive, your instinct is probably to treat the Chart view like any other SwiftUI view. You'll think, "I'll just slap a DragGesture on the whole thing, track the location of the finger, and map that X-coordinate to my data array." It sounds simple enough, and for a very basic bar chart with five bars, it might even work.
The trap of coordinate guesswork
The problem is that a Chart isn't just a rectangle of pixels; it's a complex layout of axes, labels, padding, and plot areas. If you try to calculate the selected data point by taking the gesture's location.x and dividing it by the total width of the view, you're going to be off. Why? Because your calculation includes the Y-axis labels on the left and the padding on the right. Your "selected" point will drift further and further away from the actual data point as the user moves their finger.
// The naive approach: Guessing based on view width Chart(heartRateData) { point in LineMark( x: .value("Time", point.time), y: .value("BPM", point.bpm) ) } .gesture( DragGesture().onChanged { value in // This is where it breaks. // 'value.location.x' includes the axis labels! let percent = value.location.x / totalWidth let index = Int(percent * Double(heartRateData.count)) self.selectedPoint = heartRateData[index] } )I've seen this bug pop up in countless PRs. The developer tests it on an iPhone 15, it looks "mostly okay," then they run it on an iPad or a smaller SE, and suddenly the tooltip is hovering three points to the left of where the finger actually is. It's fragile because it assumes the plot area is the same size as the view area.
Letting ChartProxy do the heavy lifting
The professional way to handle this is by using
ChartProxy. Instead of guessing where the finger is relative to the screen, you ask the chart itself to translate that screen coordinate back into the data values used by the axes. This is the "secret sauce" for building those polished, scrubbable charts you see in the Apple Health app.To do this, you use a
chartOverlay. This gives you access to aChartProxyobject, which has a method calledvalue(atX:). This method does the hard math for you: it subtracts the padding, accounts for the axis labels, and returns the actual value of the X-axis at that specific pixel location.Chart(heartRateData) { point in LineMark( x: .value("Time", point.time), y: .value("BPM", point.bpm) ) } .chartOverlay { proxy in GeometryReader { geometry in Rectangle().fill(.clear).contentShape(Rectangle()) .gesture( DragGesture().onChanged { value in // Convert the touch point to a data value if let date: Date = proxy.value(atX: value.location.x) { // Now we find the data point closest to that date self.selectedPoint = heartRateData.min(by: { abs($0.time.timeIntervalSince(date)) < abs($1.time.timeIntervalSince(date)) }) } } ) } }Balancing precision and performance
Now, you might notice that
proxy.value(atX:)returns the exact value on the axis—for example, 10:04:22 AM—but your data might only have samples every minute. This is why I usedmin(by:)in the example above. We aren't looking for an exact match (which almost never happens withDateorDouble); we're looking for the closest sample.One last tip: notice the
Rectangle().fill(.clear).contentShape(Rectangle()). If you just put a gesture on aGeometryReaderor a transparent overlay, SwiftUI sometimes ignores touches in the "empty" spaces. By adding a clear rectangle with a defined content shape, you ensure the entire chart area is hit-testable, making the scrubbing feel fluid rather than glitchy.
📋 Practical Task
Exercise: Building a Heart Rate Scrubbing Tool
Your task is to create a heart rate monitoring view that allows a user to scrub through a 24-hour data set to see the exact BPM at any given time.
- Create a
HeartRateSamplestruct withtime: Dateandbpm: Int. - Generate a mock array of 50 samples spanning a single day.
- Implement a
Chartusing aLineMarkto visualize the heart rate. - Use a
chartOverlayandChartProxyto detect aDragGesture. - As the user drags, update a
selectedSamplestate variable to the sample closest to the touch location. - Display the
selectedSample.bpmandselectedSample.timein a text label above the chart, but only when a sample is actually selected. - Bonus: Add a
RuleMarkthat moves horizontally across the chart to follow the user's finger.
There are no comments for now.