UPDATE: I updated the code to my previous semi-working solution because there were multiple answers, but none answered the question the way I need it to work.
Also, note that I need United States at the top of the picker, even if it appears again in the alphabetical country listing.
I am trying to create a picker that displays a country name, and depending on what country is selected, stores the corresponding country id. This way the user sees the name of the country but I can pass only the country id into my database.
The code I have so far shows the list of country names, and stores that country name in the selectedCountry variable. It also updates the text element in the HStack properly.
The only thing that is not working is storing the corresponding countryId.
I am using SwiftUI with the latest Swift 5 and XCode 13.1.
Here's what I've got so far:
import SwiftUI
struct Country: View {
@State private var selectedCountry = ""
@State private var selectedCountryId = ""
let countryId = Locale.isoRegionCodes
let countryArray = Locale.isoRegionCodes.compactMap { Locale.current.localizedString(forRegionCode: $0) }
var body: some view {
HStack {
Text("Country:")
.font(.system(size: 17))
Spacer()
Text("")
if selectedCountry != "" {
Text("\(selectedCountry)")
.font(.system(size: 17))
.foregroundColor(Color("WhiteText"))
} else {
Text("Select Country")
.font(.system(size: 17))
.foregroundColor(Color("GrayText"))
}
} // End HStack
.onTapGesture {
self.showsCountryPicker.toggle()
}
Picker("Country", selection: $selectedCountry) {
ForEach(countryArray, id: \.self) {
Text($0)
}
}
.pickerStyle(WheelPickerStyle())
.padding()
.labelsHidden()
}
}
}
I'm sure it's completely the wrong way to do this, so don't worry so much about correcting my code. I'd really just love to know how to do this, because I'll also need to implement the same thing when it comes to selecting a US State (i.e. show the full name of the State but store the abbreviation).
Also, there is much more to the body view, but I've stripped down the code here just to show this specific issue.
Thanks in advance!