swiftuiswiftui-listswiftui-picker

How to customize selected item checkmark icon in SwiftUI Picker in List


Using SwiftUI how can I customize the checkmark icon of the selected flavor in this simple Picker?

struct ContentView: View {
    var flavors = ["orange", "strawberry", "lemon"]
    @State private var selected: String = "orange"

    var body: some View {
        List {
            Picker("Choose a flavor", selection: $selected) {
                ForEach(flavors, id: \.self) {
                    Text($0)
                }
            }
            .pickerStyle(.inline)
        }
        
    }
}

Simple Picker


Solution

  • You'll have to create your own custom view inside a list to allow users to select options like this

    struct ContentView2: View {
        
        var flavors = ["orange", "strawberry", "lemon"]
        @State private var selected: String = "orange"
        
        var body: some View {
            List {
                ForEach(flavors, id: \.self) { flavor in
                    Button {
                        withAnimation {
                            selected = flavor
                        }
                    } label: {
                        FlavorRow(flavor: flavor, isSelected: flavor == selected)
                            .tag(flavor)
                    }
                }
            }
        }
    }
    
    struct FlavorRow: View {
        
        var flavor: String
        var isSelected: Bool
    
        var body: some View {
            HStack {
                
                Text(flavor)
                
                Spacer()
                
                if isSelected {
                    Image(systemName: "checkmark.seal")
                        .foregroundColor(.accentColor)
                }
            }
        }
    }