我需要一个多组件选择器视图,但我需要在它的最左侧添加一个新列。到目前为止,它只有我需要的三个中的两个。这是当前代码。我添加了数组,将数组包装在数组中,将变量添加为列并更改了输出。
import UIKit
class Country {
var cats: String
var country: String
var cities: [String]
init(country:String, cities:[String]) {
self.cats = cat
self.country = country
self.cities = cities
}
}
class ViewController: UIViewController, UIPickerViewDelegate, UIPickerViewDataSource {
@IBOutlet weak var pickerView: UIPickerView!
@IBOutlet weak var countryLbl: UILabel!
var countries = [Country]()
override func viewDidLoad() {
pickerView.delegate = self
pickerView.dataSource = self
cats.apppend(Cat(cat: "furry",
countries.append(Country(country: "India", cities: ["Delhi", "Ahmedabad", "Mumbai", "Pune"]))
countries.append(Country(country: "USA", cities: ["New York", "DC", "Fairfax"]))
countries.append(Country(country: "Austrailia", cities: ["Sydney", "Melbourne"]))
super.viewDidLoad()
}
func numberOfComponents(in pickerView: UIPickerView) -> Int {
return 3
}
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].country
}
else {
let selectedCountry = pickerView.selectedRow(inComponent: 0)
return countries[selectedCountry].cities[row]
}
}
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
pickerView.reloadComponent(1)
let selectedCountry = pickerView.selectedRow(inComponent: 0)
let selectedCity = pickerView.selectedRow(inComponent: 1)
let country = countries[selectedCountry].country
let city = countries[selectedCountry].cities[selectedCity]
countryLbl.text = "Country: \(country)\nCity: \(city)"
}
}
我添加了变量,但我是否添加了更多括号,然后我不知道如何识别自我,比如为什么国家 = 国家但猫不能 = 猫?此外,我要添加的第一列(行中最左侧)将只有 2 个选项,不会影响其他选项。