【问题标题】:Cannot convert value of type 'Float' to expected argument type 'Binding<Float>' Error Swift 5.2无法将“Float”类型的值转换为预期的参数类型“Binding<Float>”错误 Swift 5.2
【发布时间】:2020-04-08 15:14:36
【问题描述】:

我正在尝试使用 MVVM 模式设计重构我的代码,一切都很顺利,直到我到达我的项目属性之一,它是从 viewModel 文件发布并在 ContentView 文件中观察到的浮点数以显示百分比进度条。我对这个问题的理解非常原始,所以我需要认真的帮助。以下是我项目的 view 和 viewModel 文件中与我得到的错误相关的代码部分:

//-----------------------ContentView File

import SwiftUI


struct ContentView: View {
    @ObservedObject var quizBrain = QuizBrain()
    var body: some View {
        VStack {
            ProgressBar(barValue: quizBrain.progBarPercentage).frame(height: 35) }  
// Here I get this error: Cannot convert value of type 'Float' to expected argument type 'Binding<Float>'

struct ProgressBar: View {
    @Binding var barValue: Float
    var body: some View {
        GeometryReader { geometry in
            ZStack(alignment: .leading) {
                Rectangle().frame(width: geometry.size.width , height: geometry.size.height)
                    .opacity(0.3)
                    .foregroundColor(Color(UIColor.systemTeal))
                Rectangle().frame(width: min(CGFloat(self.barValue)*geometry.size.width, geometry.size.width), height: geometry.size.height)
                    .foregroundColor(Color(UIColor.systemBlue))
                    .animation(.linear)
            }.cornerRadius(45.0)
        }
    }
}



//--------------------ViewModel File


import Foundation

class QuizBrain: ObservableObject {
@Published var x = 10       //a method generate this Int
@Published var y = 8        //a method generate this Int
@Published var progBarPercentage : Float = 0.0

func progressBarFunc() {
      progBarPercentage = Float(y)/Float(x)
    }
}

【问题讨论】:

    标签: swift floating-point observable swiftui


    【解决方案1】:

    您必须使用 quizBrain 对象的绑定,而不是 progBarPercentage 的 Float 值。

    struct ContentView: View {
        @ObservedObject var quizBrain = QuizBrain()
        var body: some View {
            VStack {
                ProgressBar(barValue: $quizBrain.progBarPercentage).frame(height: 35)
                // Add $ to create a two way binding
            }
        }
    }
    

    【讨论】:

      【解决方案2】:

      要从@Published 值访问绑定,您应该通过“$”使用projectedValue,如下所示

      var body: some View {
          VStack {
              ProgressBar(barValue: $quizBrain.progBarPercentage).frame(height: 35) }  
      

      【讨论】:

        【解决方案3】:

        Bezi,在这种情况下,参数需要是Binding&lt;Float&gt; 类型的绑定,您缺少“$”。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2018-11-24
          • 1970-01-01
          • 2021-09-02
          • 1970-01-01
          • 1970-01-01
          • 2023-01-18
          • 1970-01-01
          相关资源
          最近更新 更多