I'm building a UIPickerView very similar to what we have in the post 3 Component Dynamic Multi UIPickerView Swift.
My code is
Class Country
import UIKit
class Country {
var name: String
var cities: [City]
init(name:String, cities:[City]) {
self.name = name
self.cities = cities
}
}
Class City
import UIKit
class City {
var name: String
init(name:String) {
self.name = name
}
}
ViewController
class ViewController: UIViewController, UIPickerViewDelegate, UIPickerViewDataSource {
@IBOutlet weak var pickerView: UIPickerView!
@IBOutlet weak var countryLbl: UILabel!
var countries = [Country]()
var newOrExisting = "New"
override func viewDidLoad() {
pickerView.delegate = self
pickerView.dataSource = self
countries.append(Country(name: "UK", cities: [City(name: "London"),City(name: "Manchester"), City(name: "Bristol")]))
countries.append(Country(name: "USA", cities: [City(name: "New York"),City(name: "Chicago")]))
countries.append(Country(name: "China", cities: [City(name: "Beijing"),City(name: "Shanghai"), City(name: "Shenzhen"), City(name: "Hong Kong")]))
super.viewDidLoad()
if newOrExisting == "Existing" {
// here I need to load existing Country and City to the UIPickerView (for example, USA and Chigado) based on their names
// newOrExisting status is updated in another ViewController. For example, let's assume it came as "existing"
}
}
func numberOfComponents(in pickerView: UIPickerView) -> Int {
return 2
}
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
if component == 0 {
return countries.count
} else {
let selectedCountry = pickerView.selectedRow(inComponent: 0)
return countries[selectedCountry].cities.count
}
}
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
if component == 0 {
return countries[row].name
} else {
let selectedCountry = pickerView.selectedRow(inComponent: 0)
return countries[selectedCountry].cities[row].name
}
}
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
pickerView.reloadAllComponents
let selectedCountry = pickerView.selectedRow(inComponent: 0)
let selectedCity = pickerView.selectedRow(inComponent: 1)
let cityR = countries[selectedCountry].cities[selectedCity].name
countryLbl.text = "The right answer was: \(selectedCountry) in \(cityR)"
}
}
Note: I haven't added my comments there because, as I have less than 50 reputations, I cannot comment.
With the above code, I can add data to my UIPickerView and read data from it. I then store that data to a Firebase database. There I'll have, for example, Country name "USA" and the City name "Chicago".
But, I now need to do the opposite path. If I read "USA" and "Chicago" from the database, how do I select those in the UIPickerView just using their names? I don't have the indexes in my database. Is there a way to do it?
Thanks