You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
structMonthlySalesChart:View{varbody:someView{Chart(data, id: \.month){BarMark(
x:.value("Month", $0.month, unit:.month),
y:.value("Sales", $0.sales))}.chartXAxis{AxisMarks(values:.stride(by:.month)){ value in
if value.as(Date.self)!.isFirstMonthOfQuarter {AxisGridLine().foregroundStyle(.black)AxisTick().foregroundStyle(.black)AxisValueLabel(
format:.dateTime.month(.narrow))}else{AxisGridLine()}}}}}
可交互图表示例如下:
structInteractiveBrushingChart:View{@Statevarrange:(Date,Date)?=nilvarbody:someView{Chart{ForEach(data, id: \.day){LineMark(
x:.value("Month", $0.day, unit:.day),
y:.value("Sales", $0.sales)).interpolationMethod(.catmullRom).symbol(Circle().strokeBorder(lineWidth:2))}
if let(start, end)= range {RectangleMark(
xStart:.value("Selection Start", start),
xEnd:.value("Selection End", end)).foregroundStyle(.gray.opacity(0.2))}}.chartOverlay{ proxy inGeometryReader{ nthGeoItem inRectangle().fill(.clear).contentShape(Rectangle()).gesture(DragGesture().onChanged{ value in// Find the x-coordinates in the chart’s plot area.letxStart= value.startLocation.x - nthGeoItem[proxy.plotAreaFrame].origin.x
letxCurrent= value.location.x - nthGeoItem[proxy.plotAreaFrame].origin.x
// Find the date values at the x-coordinates.
if let dateStart:Date= proxy.value(atX: xStart),let dateCurrent:Date= proxy.value(atX: xCurrent){
range =(dateStart, dateCurrent)}}.onEnded{ _ in range =nil}// Clear the state on gesture end.)}}}}
可视化数据,使用 SwiftUI 语法来创建。还可以使用 ChartRenderer 接口将图标渲染成图。
官方文档 Swift Charts
入门参看 Hello Swift Charts
Apple 文章 Creating a chart using Swift Charts
高级定制和创建更精细图表,可以看这个 session Swift Charts: Raise the bar 这个 session 也会提到如何在图表中进行交互。这里是 session 对应的代码示例 Visualizing your app’s data 。
图表设计的 session,Design an effective chart 和 Design app experiences with charts 。
下面是一个简单的代码示例:
BarMark 用于创建条形图,LineMark 用于创建折线图。SwiftUI Charts 框架还提供 PointMark、AxisMarks、AreaMark、RectangularMark 和 RuleMark 用于创建不同类型的图表。注释使用
.annotation
modifier,修改颜色可以使用.foregroundStyle
modifier。.lineStyle
modifier 可以修改线宽。AxisMarks 的示例如下:
可交互图表示例如下:
社区做的更多 Swift Charts 范例 Swift Charts Examples 。
The text was updated successfully, but these errors were encountered: