【问题标题】:@State not updating SwiftUI@State 不更新 SwiftUI
【发布时间】:2021-03-13 05:51:43
【问题描述】:

我对 Swift 和 SwiftUI 还很陌生,所以这可能有一些我忽略的明确答案。我的目标是每次单击按钮时都会更新此进度环。我希望按钮将DailyGoalProgress 更新某个数字,这很有效。但是,我还希望 DailyGoalProgress 然后除以一个数字来得到这个 @State。正如我所说,DailyGoalProgress 更新但@State 没有,我无法弄清楚我做错了什么。任何帮助是极大的赞赏。谢谢!

这是我的代码的缩写版本:

struct SummaryView: View {
    
    @AppStorage ("DailyGoalProgress") var DailyGoalProgress: Int = 0
    @State var progressValue: Float = 0 //This just stays at zero and never changes even with the button press
    var body: some View {
       ProgressBar(progress: self.$progressValue, DailyGoalProgress: self.$DailyGoalProgress)     
    }
}

这是另一种观点:

@Binding var DailyGoalProgress: Int
@Binding var progressValue: Float
var body: some View {

    Button(action: {DailyGoalProgress += tokencount; progressValue = Float(DailyGoalProgress / 30)}) {
                            Text("Mark This Task As Completed")
                                .font(.title3)
                                .fontWeight(.semibold)
                                .foregroundColor(Color.white)
                        }
                    }.frame(width: 330.0, height: 65.0).padding(.bottom, 75.0)
                    Spacer()
                }.padding(.top, 125.0)
            }
            
            
            Spacer()
        }
    }
}

【问题讨论】:

  • 您是否需要两个不同的变量来跟踪进度?你可以单独使用@AppStorage。
  • @TusharSharma 我也单独显示DailyGoalProgress,所以是的,我两者都需要。

标签: ios swift swiftui state


【解决方案1】:

您的问题是关于 Int to FloatDailyGoalProgressInt,您应该先将其转换为 Float然后除以 30.0 就可以了。

这叫推理! Swift 希望以它自己的方式帮助你,但它给你带来了麻烦。

如果您想详细了解会发生什么:当您将 DailyGoalProgress 除以 30 时,结果是什么,它将被视为 Int,那是什么意思? 0 到 1 之间的平均数总是 0,然后你把 0 给 Float,也没有任何反应!

import SwiftUI

struct ContentView: View {
    
    @AppStorage ("DailyGoalProgress") var DailyGoalProgress: Int = 0
    @State var progressValue: Float = 0

    var body: some View {
        
        Spacer()
        
        Text(DailyGoalProgress.description)
        
        Text(progressValue.description)

        ProgressBar(DailyGoalProgress: $DailyGoalProgress, progressValue: $progressValue)

        Spacer()
        
    }
}


struct ProgressBar: View {
    
    @Binding var DailyGoalProgress: Int
    @Binding var progressValue: Float
    
    let tokencount: Int = 30  // <<: Here for example I used 30

    var body: some View {

        Button(action: {
            
            DailyGoalProgress += tokencount
            progressValue = Float(DailyGoalProgress)/30.0 // <<: Here
            
        }, label: {
            
            Text("Mark This Task As Completed")
                .font(.title3)
                .fontWeight(.semibold)

        })
        
 
    }
    
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-08-06
    • 2021-01-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-21
    • 1970-01-01
    相关资源
    最近更新 更多