我正在构建一个UIPickerView,与我们在帖子中非常相似 3 Component Dynamic Multi UIPickerView Swift。
我的代码是
国家/地区
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)"
}
}
注意:我之所以没有在此处添加评论,是因为我的声誉不到50个,因此无法发表评论。
使用上面的代码,我可以将数据添加到UIPickerView并从中读取数据。 然后,我将该数据存储到Firebase数据库中。例如,我在那里会有国家名称“ USA”和城市名称“ Chicago”。
但是,我现在需要走相反的道路。如果我从数据库中读取了“美国”和“芝加哥”,如何仅使用名称在UIPickerView中选择它们?我的数据库中没有索引。 有办法吗?
谢谢