我正在尝试创建一组三个选择器视图,其数据值取决于前一个视图。因此,例如,在第一个选择器视图中,您可以选择A,B和& C并根据选择,第二个选择器视图将显示X,Y或Z数据。第三个也是如此。如果在先前视图中未选择任何内容,则其余视图将显示空白字符串。用户可以通过单击三个不同的文本视图中的一个来独立访问每个选择器(即一次只显示一个选择器视图)。
这是我已经制作的相关代码。它有点工作,但有一些错误,我想知道是否有人可以帮我改善它。选择器视图允许用户在(A)他/她所居住的国家,(B)州和(C)城市之间进行选择。所有这些值都存储在3个词典中:
override func viewDidLoad() {
super.viewDidLoad()
countryPickerView = UIPickerView()
statePickerView = UIPickerView()
cityPickerView = UIPickerView()
countryPickerView.delegate = self
statePickerView.delegate = self
cityPickerView.delegate = self
countryPickerView.dataSource = self
statePickerView.dataSource = self
cityPickerView.dataSource = self
countryPickerView.tag = 0
statePickerView.tag = 1
cityPickerView.tag = 2
countryTextField.inputView = countryPickerView
stateTextField.inputView = statePickerView
cityTextField.inputView = cityPickerView
}
// Declares the number of separate components (NOT entries) in all picker views
func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int {
return 1
}
// Declares the number of entries in each picker view
func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
if pickerView.tag == 0 {
return Locations.getAllCountries().count
} else if pickerView.tag == 1 {
if chosenCountry != nil && chosenCountry != "" {
return Locations.getAllStatesForCountry(chosenCountry!).count
} else {
return 1
}
} else if pickerView.tag == 2 {
if chosenState != nil && chosenState != "" {
return Locations.getAllCitiesForState(chosenState!).count
} else {
return 1
}
}
return 1
}
// Declares the text in each entry in each picker view
// Will be a blank string if the previous picker hasn't been selected yet
func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String! {
if pickerView.tag == 0 {
return Locations.getAllCountries()[row]
} else if pickerView.tag == 1 {
if chosenCountry != nil && chosenCountry != "" {
return Locations.getAllStatesForCountry(chosenCountry!)[row]
}
} else if pickerView.tag == 2 {
if chosenState != nil && chosenState != "" {
return Locations.getAllCitiesForState(chosenState!)[row]
}
}
return ""
}
// Sets the textfields to display the chosen text
func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
if pickerView.tag == 0 {
countryTextField.text = Locations.getAllCountries()[row]
chosenCountry = countryTextField.text!
} else if pickerView.tag == 1 {
if chosenCountry != nil && chosenCountry != "" {
stateTextField.text = Locations.getAllCitiesForState(chosenState!)[row]
chosenState = stateTextField.text!
} else {
stateTextField.text = ""
}
} else if pickerView.tag == 2 {
if chosenState != nil && chosenState != "" {
cityTextField.text = Locations.getAllCitiesForState(chosenState!)[row]
chosenCity = cityTextField.text!
} else {
cityTextField.text = ""
}
}
}
我对Swift和iOS仍然很新,所以如果这是一个次优的解决方案,请耐心等待。有没有人这样做过?