Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SwiftUI Picker in a Form doesn't show the selected row

I am trying to have a Picker that shows which option is currently selected.

Try out the following code which correctly selects the right option but the picker does not show which option is selected:

import SwiftUI

struct ContentView: View {
@State var selectedIndex: Int = 0

let strings: [String] = {
    var strings: [String] = []
    for i in 0..<10 {
        strings.append("\(i)")
    }
    return strings
}()

var body: some View {
    NavigationView {
        VStack {
            Form {
                Picker(selection: $selectedIndex,
                       label: Text("Selected string: \(strings[selectedIndex])")) {
                    ForEach(0..<strings.count) {
                        Text(self.strings[$0]).tag($0)
                    }
                }
            }
        }
        .navigationBarTitle("Form Picker",
                            displayMode: NavigationBarItem.TitleDisplayMode.inline)
    }
}

}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

Anyone know what could be wrong? It's observed using Xcode 11.1 and iOS 13.1

like image 761
Jose Castellanos Avatar asked Oct 16 '19 05:10

Jose Castellanos


Video Answer


1 Answers

I created the simple picker I call "ListPicker" which should fit the bill. I've written it so it works well in a Form; if you need it outside of a Form you will have to tinker with it. If you see any way to improve the code, please add a comment; this is still a learning experience for all of us.

// MARK: - LIST PICKER (PUBLIC)

struct ListPicker<Content: View>: View {
    @Binding var selectedItem: Int
    var label: () -> Content
    var data: [Any]

    var selectedLabel: String {
        selectedItem >= 0 ? "\(data[selectedItem])" : ""
    }

    var body: some View {
        NavigationLink(destination: ListPickerContent(selectedItem: self.$selectedItem, data: self.data)) {
            ListPickerLabel(label: self.label, value: "\(self.selectedLabel)")
        }
    }
}

// MARK: - INTERNAL

private struct ListPickerLabel<Content: View>: View {
    let label: () -> Content
    let value: String

    var body: some View {
        HStack(alignment: .center) {
            self.label()
            Spacer()
            Text(value)
                .padding(.leading, 8)
        }
    }
}

private struct ListPickerContentItem: View {
    let label: String
    let index: Int
    let isSelected: Bool
    var body: some View {
        HStack {
            Text(label)
            Spacer()
            if isSelected {
                Image(systemName: "checkmark")
                    .foregroundColor(.accentColor)
            }
        }.background(Color.white) // so the entire row is selectable
    }
}

private struct ListPickerContent: View {
    @Environment(\.presentationMode) var presentationMode
    @Binding var selectedItem: Int
    var data: [Any]
    var body: some View {
        List {
            ForEach(0..<data.count) { index in
                ListPickerContentItem(label: "\(self.data[index])", index: index, isSelected: index == self.selectedItem).onTapGesture {
                    self.selectedItem = index
                    self.presentationMode.wrappedValue.dismiss()
                }
            }
        }
    }
}

Then you can use it like this:

@State var selectedCar: Int = 0
let cars = ["Jaguar", "Audi", "BMW", "Land Rover"]

Form {
    ListPicker(
        selectedItem: self.$selectedCar, 
        label: {
            Text("Cars")
        }, 
        data: self.cars
    )
}
like image 90
P. Ent Avatar answered Sep 25 '22 18:09

P. Ent