1

I have a Binding like this:

@State var entires: [Entry]

Where Entry has one property called amount which is a float.

Now I'm trying to add it to a TextField inside a List:

List {
    ForEach(entries, id: \.self) { (entry: Entry) in
        TextField("Amount", text: "\(entry.amount)")
    }
}

Then its telling me that its a String and not Binding<String>. But where to place the $ to have it right?

2 Answers 2

1

Here is a demo of possible solution (tested with Xcode 11.4 / iOS 13.4)

struct Entry {
    var amount: Float
}

struct ContentView: View {
    @State var entries: [Entry] = [Entry(amount: 1.0)]
    var body: some View {
        List {
            ForEach(entries.indices, id: \.self) {
                self.row(for: $0)
            }
        }
    }

    func row(for index: Int) -> some View {
        let text = Binding<String>(
            get: { String(self.entries[index].amount) },
            set: { self.entries[index].amount = Float($0) ?? 0 }
        )
        return TextField("Amount", text: text)
    }
}
Sign up to request clarification or add additional context in comments.

Comments

1

You need to define a create a Binding yourself that does the Float-String conversion. You can achieve this using the Binding(get:set:) initialiser.

You also need to call ForEach on entries.indices and access each Entry by index, since the loop variable is immutable, so you couldn't pass entry directly to a mutable Binding if you iterated over entries instead of entries.indices.

ForEach(entries.indices, id: \.self) { index -> TextField<Text> in
    let binding = Binding<String>(
        get: { self.entries[index].amount.description },
        set: { if let newValue = Float($0) { self.entries[index].amount = newValue }}
    )
    return TextField("Amount", text: binding)
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.