SwiftUI picker separate texts for selected item and selection view

Possible solution without a Picker

As mention in my comment, there is not yet a solution for a native implementation with the SwiftUI Picker. Instead, you can do it with SwiftUI Elements especially with a NavigationLink. Here is a sample code:

struct Item {
    let abbr: String
    let desc: String
}

struct ContentView: View {
    
    @State private var selectedIndex = 0
    let items: [Item] = [
        Item(abbr: "AA", desc: "aaaaa"),
        Item(abbr: "BB", desc: "bbbbb"),
        Item(abbr: "CC", desc: "ccccc"),
    ]
    
    var body: some View {
        NavigationView {
            Form {
                NavigationLink(destination: (
                    DetailSelectionView(items: items, selectedItem: $selectedIndex)
                    ), label: {
                        HStack {
                            Text("Chosen item")
                            Spacer()
                            Text(self.items[selectedIndex].abbr).foregroundColor(Color.gray)
                        }
                })
            }
        }
    }
}

struct DetailSelectionView: View {
    var items: [Item]
    @Binding var selectedItem: Int
    
    var body: some View {
        Form {
            ForEach(0..<items.count) { index in
                HStack {
                    Text(self.items[index].desc)
                    Spacer()
                    if self.selectedItem == index {
                        Image(systemName: "checkmark").foregroundColor(Color.blue)
                    }
                }
                .onTapGesture {
                    self.selectedItem = index
                }
            }
        }
    }
}

If there are any improvements feel free to edit the code snippet.

Leave a Comment