Following your method,
I added some enhancements, I added margin on the left and proper facet, permitting a correct choice when scrolling, additionally outlined a scrollPosition which is Int
to trace the index chosen of your information.
If you wish to change the worth proven on prime you solely want to change the selectionText
operate to return .worth
should you want
hope that is what you’re asking for.
import SwiftUI
import Charts
struct SampleModel: Identifiable {
var id = UUID()
var date: String
var worth: Double
var animate: Bool = false
}
struct ContentView: View {
@State non-public var information = [
SampleModel(date: "26nFr", value: 9.2),
SampleModel(date: "27nSa", value: 12.5),
SampleModel(date: "28nSu", value: 15.0),
SampleModel(date: "29nMo", value: 20.0),
SampleModel(date: "30nTu", value: 5.0),
SampleModel(date: "31nWe", value: 7.0),
SampleModel(date: "01nTh", value: 3.0),
SampleModel(date: "02nFr", value: 20.0),
SampleModel(date: "03nSa", value: 5.0),
SampleModel(date: "04nSu", value: 7.0),
SampleModel(date: "05nMo", value: 3.0),
SampleModel(date: "06nTu", value: 10.0),
SampleModel(date: "07nWe", value: 21.0),
SampleModel(date: "08nTh", value: 14.0),
SampleModel(date: "09nFr", value: 10.0),
SampleModel(date: "10nSt", value: 7.0),
SampleModel(date: "11nSu", value: 15.0),
SampleModel(date: "12nMo", value: 17.0),
SampleModel(date: "13nTu", value: 29.0)
]
@State non-public var scrollPosition: Int = 0
@State var priceText: String? = nil
@State var selectedIndex: Int = 0
var physique: some View {
GeometryReader { geometry in
VStack {
if let worth = priceText {
Textual content(worth)
.padding()
}
Textual content(selectionText())
.padding()
Chart(Array(zip(information.indices, information)), id: .0) { index, flight in
BarMark(x: .worth("Index", index),
y: .worth("Value", flight.worth), width: .fastened(10))
.foregroundStyle(
Gradient(
colours: [
.blue,
.green
]
)
)
.clipShape(RoundedRectangle(cornerRadius: 16))
}
.body(top: 180)
.background(content material: {
VStack {
Coloration.grey.body(width: 1)
Coloration.clear.body(top: 40)
}
})
.chartXAxis(content material: {
AxisMarks(preset: .aligned, place: .backside, values: .stride(by: 1)) { worth in
let label = information[value.index].date
AxisValueLabel(label)
.foregroundStyle(.grey)
}
})
.chartXVisibleDomain(size: 10)
.chartYAxis(.hidden)
.chartScrollTargetBehavior(
.valueAligned(unit: 1)
)
.chartScrollableAxes(.horizontal)
.chartScrollPosition(x: $scrollPosition)
.contentMargins(Edge.Set(arrayLiteral: [.leading, .trailing]), geometry.measurement.width/2)
}
}
}
non-public func selectionText() -> String {
guard scrollPosition >= .zero else {
return information[.zero].date
}
guard scrollPosition < information.rely else {
return information[data.count - 1].date
}
return information[scrollPosition].date
}
}