下記のコードについての質問です。
体重入力後に保存ボタンを押すと、その値が折れ線グラフになるようにしたいです。
現時点で折れ線グラフにはなるのですが、一度画面を閉じて再度アプリを開かないと描画されません。
これを、保存ボタン押した後すぐに再描画されるようにしたいです。
func updateUIViewで再描画すると推測しているのですが、その方法が分かりません。
リロードなども書いてみましたが、エラーが出て実行できませんでした。
何かアイデアでもいただけたらと思います。よろしくお願いします。
swift
1import SwiftUI 2import Charts 3 4struct WeightPage2: View{ 5 @State var weight = "" 6 @State var weightarray:[String] 7 8 var body: some View{ 9 TextField("今日の体重",text:$weight).textFieldStyle(RoundedBorderTextFieldStyle()).frame(width:120).overlay(RoundedRectangle(cornerRadius:1).stroke(Color.black, lineWidth:1)) 10 Button(action:{weightarray.append(weight);UserDefaults.standard.set(weightarray, forKey: "weightkey")}){ 11 Text("保存する") 12 } 13 LineChart(weightarray:$weightarray).frame(width:360 ,height: 400) 14 } 15 init() { 16 let w = UserDefaults.standard.array(forKey: "weightkey") as? [String] ?? [] 17 _weightarray = State(initialValue: w) 18 } 19} 20 21struct LineChart : UIViewRepresentable { 22 typealias UIViewType = LineChartView 23 @Binding var weightarray:[String] 24 25 func makeUIView(context: Context) -> LineChartView { 26 let lineChartView = LineChartView() 27 lineChartView.data = setData() 28 29 return lineChartView 30 } 31 func updateUIView(_ uiView: LineChartView, context: Context) { 32 33 } 34 func setData() -> LineChartData{ 35 let dataPoint = getDataPoints() 36 let set = LineChartDataSet(entries: dataPoint, label: "My data") 37 let data = LineChartData(dataSet: set) 38 return data 39 } 40 func getDataPoints() -> [ChartDataEntry] { 41 var dataPoints: [ChartDataEntry] = [] 42 for count in 0..<weightarray.count{ 43 dataPoints.append(ChartDataEntry(x:Double(count),y: Double(weightarray[count]) ?? 0)) 44 } 45 return dataPoints 46 } 47} 48 49struct WeightPage2_Previews: PreviewProvider { 50 static var previews: some View { 51 WeightPage2() 52 } 53}
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2022/06/16 14:56