Last active
December 3, 2021 18:58
-
-
Save zentrope/cfe503e65e6e106e773884d34aec6e63 to your computer and use it in GitHub Desktop.
Pseudo example for locale picker
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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