Skip to content

Instantly share code, notes, and snippets.

@atrinh0
Created August 6, 2022 16:50
Show Gist options
  • Save atrinh0/3df23140ba39df05692befb7153c8285 to your computer and use it in GitHub Desktop.
Save atrinh0/3df23140ba39df05692befb7153c8285 to your computer and use it in GitHub Desktop.
SwiftUI menu picker selection issue
import SwiftUI
struct ContentView: View {
@State private var selection: SortOrder = .ascending
var body: some View {
NavigationView {
VStack {
Text("Selected Sort Order:")
Text(selection.rawValue)
.font(.largeTitle)
Picker(selection: $selection) {
ForEach(SortOrder.allCases) {
Text($0.rawValue)
.tag($0)
}
} label: { }
.pickerStyle(.segmented)
.padding()
}
.toolbar {
Menu {
Picker(selection: $selection) {
ForEach(SortOrder.allCases) {
Text($0.rawValue)
.tag($0)
}
} label: { }
} label: {
Text("Sort by")
}
}
}
}
}
enum SortOrder: String, CaseIterable, Identifiable {
case ascending = "Ascending"
case descending = "Descending"
case high = "High"
case low = "Low"
var id: String { self.rawValue }
}
@atrinh0
Copy link
Author

atrinh0 commented Aug 16, 2022

A workaround, https://twitter.com/DanielKasaj/status/1559453531760992257

Setting the .id(UUID()) on the menu fixes the selection issue.

Menu {
    Picker(selection: $selection) {
        ForEach(SortOrder.allCases) {
            Text($0.rawValue)
                .tag($0)
        }
    } label: { }
} label: {
    Text("Sort by")
}
.id(UUID())

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment