Home > database >  SwiftUI Setting Bind<String> in Text field
SwiftUI Setting Bind<String> in Text field

Time:02-10

I've got the following object that contain list of strings:

class handler: ObservableObject {
  @Published var items = [String]()
}

In some closure, I set this list with valid values :

for item in item_list! {
  self.handler.items.append(item.stringData)
}

and in the ContentView part I've got Picker that support to present that list of strings in realtime:

VStack {
  Picker("items", selection: $arg1) {
    ForEach($handler.items, id: \.self) {
      Text($0)
    }
  }
}

However, it fails to compile due to the following reason :

Initializer 'init(_:)' requires that 'Binding<String>' conform to 'StringProtocol'

Any Idea how to resolve this ?

CodePudding user response:

You don't need binding here to loop items, instead use handler directly (ie. without $), like

ForEach(handler.items, id: \.self) {    // << here !!
  Text($0)
}
  • Related