La traduction a été préparée dans le cadre du cours "Développeur iOS. Basique" . Si vous souhaitez en savoir plus sur le cours, rendez-vous à la journée portes ouvertes en ligne.
De temps en temps, j'ai besoin de visualiser des données sous forme de beaux graphiques. Cet article vous montrera comment dessiner des graphiques dans une application SwiftUI.
- , .
XCode.
SwiftUI-, .
, .
"", . : https://github.com/spacenation/swiftui-charts.git.
.
, .
. Github-Readme ContentView
:
import Charts
import SwiftUI
struct ContentView: View {
var body: some View {
Chart(data: [0.1, 0.3, 0.2, 0.5, 0.4, 0.9, 0.1])
.chartStyle(
LineChartStyle(.quadCurve, lineColor: .blue, lineWidth: 5)
)
}
}
, .
.
, , , , , , . , .
"" ObservableObject
, Double
500 .
import Foundation
class ValuePublisher: ObservableObject {
@Published var value: Double = 0.0
init() {
Timer.scheduledTimer(withTimeInterval: 0.5, repeats: true) { timer in
self.value = Double.random(in: 0...1.0)
}
}
}
ContentView
@State
.
@StateObject var valuePublisher = ValuePublisher()
ValuePublisher
, , . .
struct Queue<T> {
var list = [T]()
mutating func enqueue(_ element: T) {
list.append(element)
}
mutating func dequeue() -> T? {
if !list.isEmpty {
return list.removeFirst()
} else {
return nil
}
}
func peek() -> T? {
if !list.isEmpty {
return list[0]
} else {
return nil
}
}
}
@State
ContentView
@State var doubleQueue = Queue<Double>()
.
.onAppear {
doubleQueue.list = [Double](repeating: 0.0, count: 50)
}
, .
Chart(data: doubleQueue.list)
ValuePublisher
, .
.onChange(of: valuePublisher.value) { value in
self.doubleQueue.enqueue(value)
_ = self.doubleQueue.dequeue()
}
, ContentView
, .
import Charts
import SwiftUI
struct ContentView: View {
@State var doubleQueue = Queue<Double>()
@StateObject var valuePublisher = ValuePublisher()
var body: some View {
Chart(data: doubleQueue.list)
.chartStyle(
AreaChartStyle(.quadCurve, fill:
LinearGradient(gradient: .init(colors: [Color.blue.opacity(1.0), Color.blue.opacity(0.5)]), startPoint: .top, endPoint: .bottom)
)
)
.onAppear {
doubleQueue.list = [Double](repeating: 0.0, count: 50)
}
.onChange(of: valuePublisher.value) { value in
self.doubleQueue.enqueue(value)
_ = self.doubleQueue.dequeue()
}
.padding()
}
}
, , , .
: SwiftUI