Reusable SwiftUI Picker view

Viewed 16

I am trying to create a reusable picker and am stumped with getting the foreach loop to function correctly.

I am getting two Errors

  • Generic struct 'ForEach' requires that 'String' conform to 'RandomAccessCollection'

  • No exact matches in call to initializer

      struct PickerSlector: View {
      var title: String
      @Binding var selection: String
      @Binding var item: String
    
      init(_ title: String, selection: Binding<String>, item: Binding<String>){
          self.title = title
          self._selection = selection
          self._item = item
      }
    
    
      var body: some View {
          Picker("", selection: $selection){
              ForEach (item, id: \.self) {
                  Text($0)
              }
          }
          .font(Font.custom(Design.PrimaryFont, size: 16))
          .foregroundColor(selection == "Select" ? Color(Design.TextDark!) : Color(Design.accent!))
      }
    

    }

1 Answers

The ForEach is trying to iterate over a String, while it should iterate over an array (or some kind of sequence, here I use an array to show how it can work).

Replace item: String with items: [String] and correct the rest of the code:

struct PickerSelector: View {      // <- Correct typo in Slector
    var title: String
    @Binding var selection: String
    @Binding var items: [String]      // <- Change here
    
    init(_ title: String, selection: Binding<String>, items: Binding<[String]>){      // <- Correct the initializer
        self.title = title
        self._selection = selection
        self._items = items      // <- More appropriate variable name
    }
    
    
    var body: some View {
        Picker("", selection: $selection){
            ForEach(items, id: \.self) {      // <- Update variable name here
                Text($0)
            }
        }
        .font(Font.custom(Design.PrimaryFont, size: 16))
        .foregroundColor(selection == "Select" ? Color(Design.TextDark!) : Color(Design.accent!))
    }
}
Related