简体   繁体   中英

TextField: Generic parameter 'Subject' could not be inferred

I have a form view designed to edit data for an existing item and I'm able to display the Binded (bound?) value without a problem. The TextField gives me an error of "Generic parameter 'Subject' could not be inferred"

Here's the file where the problem is occurring.

import SwiftUI


struct EditMeasurementView: View {

    @Binding var measurementItem: MeasurementItem

    var body: some View {
        Form {
            Text("\(measurementItem.weight)")
            TextField("Weight", text: $measurementItem.weight)
            // TextField("Date", text: $measurementItem.mdate)
        }
    }
}

struct EditMeasurementView_Previews: PreviewProvider {
    static var previews: some View {
        EditMeasurementView(measurementItem:  .constant(MeasurementItem(weight:"99",mdate:"1/1/2001")))
    }
}

The first item in the form is fine and if I click on '$measurementItem' is is bound to the @Binding. The second item is where the error appears and if I click on '$measurementItem' there, it does not indicate is is linked back to the @Binding.

What am I missing?

Here is some code to duplicate the problem described above:

import SwiftUI

struct MeasurementItem {
    let weight: String
    let mdate: String
}

struct EditMeasurementView: View {
    @State var measurementItem: MeasurementItem

    var body: some View {
        Form {
            Text("\(measurementItem.weight)")
            TextField("Weight", text: $measurementItem.weight)
        }
    }
}

struct EditMeasurementView_Previews: PreviewProvider {
    static var previews: some View {
        EditMeasurementView(measurementItem:  MeasurementItem(weight:"99",mdate:"1/1/2001"))
    }
}

The line TextField("Weight", text: $measurementItem.weight) will generate the error described by the OP.

However the real problem is not with TextField("Weight", text: $measurementItem.weight) itself but that $measurementItem.weight is a constant (ie it is declared with let instead of var ) and because it's a constant the TextField cannot change the value of $measurementItem.weight .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM