TEAM LICENSES: Save money and learn new skills through a Hacking with Swift+ team license >>

Error with binding in a TextField

Forums > SwiftUI

Not sure what I'm doing wrong here. The binding for role.hourlyCost gives the error that it is not in scope while the text filed does not. I'm sure this basic but I'm stumped.

import SwiftUI import SwiftData

struct SampleView: View {

@Query(sort: \roleModel.role) var roles: [roleModel]
@State var selection: String = ""

var body: some View {
    NavigationStack {
        List (selection: $selection) {
            ForEach (roles, id: \.self) {role in
                VStack (alignment: .leading) {
                    Text(role.hourlyCost)
                    //THE ABOVE WORKS AS EXPECTED
                    TextField("Hourly", value: $role.hourlyCost, format: .currency(code: Locale.current.currency?.identifier ?? "USD"))
                    //THE ABOVE GIVES AN ERROR : Cannot find '$role' in scope
                }
            }
        }
    }
}

}

2      

TextField require a Binding value, however role.hourlyCost is not

So add

@State private var hourlyCost = 0

then

TextField("hourly", value: $hourlyCost, format: .currency(code: Locale.current.currency?.identifier ?? "USD"))

then on submit save it to SwiftData

2      

Hacking with Swift is sponsored by RevenueCat.

SPONSORED Take the pain out of configuring and testing your paywalls. RevenueCat's Paywalls allow you to remotely configure your entire paywall view without any code changes or app updates.

Learn more here

Sponsor Hacking with Swift and reach the world's largest Swift community!

Reply to this topic…

You need to create an account or log in to reply.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.