Home > Software design >  Button within ForEach Loop
Button within ForEach Loop

Time:12-02

I am creating an autocomplete search TextField. Currently, it is a VStack of categories and I want the user to tap a category to select it, and have the category become the TextField value.

This code works, but it is just text and nothing happens on tap:

var body: some View {
...
    Form {
        ...
        ForEach(observed.results, id: \.id) {
                Text($0.result).foregroundColor(.gray)
        }
        ...
    }
...
}

When I try to turn them into buttons, XCode throws a Trailing closure passed to parameter of type 'FormStyleConfiguration' that does not accept a closure error. $search is the TextField's text attribute value.

@State private var search: String = ""
...
func setSearch(selected: String) {
        self.search = selected
    }
...
var body: some View {
...
    Form {
        ...
        ForEach(observed.results, id: \.id) {
            Button( action: { self.setSearch(selected: $0.result) }) {
                Text($0.result).foregroundColor(.gray)
            }
        }
        ...
    }
...
}

How can I change state to update text field on tap?

CodePudding user response:

  1. Changing my Form to List produced more descriptive errors.
  2. Used an explicit argument for my ForEach loop.
  • I intended $0 to be an implicit argument from my ForEach loop. However, when used within another closure, e.g. Button { } or .onTapGesture() { }, the nested closure threw an error believing the implicit argument to belong to itself.
  • Related