Skip to content

Instantly share code, notes, and snippets.

@zentrope
Last active December 3, 2021 18:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zentrope/cfe503e65e6e106e773884d34aec6e63 to your computer and use it in GitHub Desktop.
Save zentrope/cfe503e65e6e106e773884d34aec6e63 to your computer and use it in GitHub Desktop.
Pseudo example for locale picker
import SwiftUI
// Can be in another file
struct DataManager {
static let shared = DataManager()
static let defaultRegionCode = "US"
var countries: [Country] {
get {
let usa = Country(id: defaultRegionCode, name: Locale.current.localizedString(forRegionCode: defaultRegionCode) ?? defaultRegionCode)
let others = Locale.isoRegionCodes
.filter { $0 != defaultRegionCode}
.map { Country(id: $0, name: Locale.current.localizedString(forRegionCode: $0) ?? $0) }
.sorted(by: {$0.name < $1.name})
return [usa] + others
}
}
struct Country: Identifiable {
var id: String
var name: String
}
}
struct ContentView: View {
@State private var selectedCountry: String = DataManager.defaultRegionCode
var body: some View {
VStack(alignment: .leading) {
HStack {
Text("Selected code: ")
Text("\(Locale.current.localizedString(forRegionCode: selectedCountry) ?? selectedCountry) (\(selectedCountry))")
Spacer()
}
Picker("", selection: $selectedCountry) {
ForEach(DataManager.shared.countries, id: \.id) { country in
Text(country.name).tag(country.id)
}
}
}
.fixedSize()
.padding()
.frame(width: 500, alignment: .leading)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment