当前版本的图片我目前有两个选择器视图。一个是国家选择器视图(美国和加拿大),另一个是州选择器视图。I'd like to have it so when USA is selected it displays US states, and when Canada is selected, Canadian provinces are displayed. 这是我到目前为止所拥有的示例。非常感谢您的帮助!
编辑:仍然没有找到任何有效的解决方案,任何帮助将不胜感激!
let countries = ["",
"USA",
"Canada",
]
let states = ["Alaska",
"Alabama",
"Arkansas"]
let provinces = ["Alberta",
"British Columbia",
"Manitoba",
"New Brunswick"]
//Sets picker view
let pickerView = UIPickerView()
//Holds current data in array
var currentArray: [String] = []
//Holds current text field
var activeTextField : UITextField!
var activeField: UITextField?
fileprivate func delegates() {
countryTextView.delegate = self
stateTextView.delegate = self
}
fileprivate func pickerViewDelegates() {
//Enables pickerview
pickerView.delegate = self
pickerView.dataSource = self
}
//Sets pickerview input
fileprivate func pickerViewSet() {
countryTextView.inputView = pickerView
stateTextView.inputView = pickerView
}
//Closes keyboard when done button is pressed
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
textField.resignFirstResponder()
return true
}
//Textfield delegate
func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool {
activeTextField = textField
switch textField {
case countryTextView:
currentArray = countries
case stateTextView:
currentArray = states
default:
print("Default")
}
pickerView.reloadAllComponents()
return true
}
//Number of rows in picker view
func numberOfComponents(in pickerView: UIPickerView) -> Int {
return 1
}
//One element of array per row
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
return currentArray.count
}
//Puts the array element of whichever picker view is chosen into picker view
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String?{
return currentArray[row]
}
//Selects the array element in the row thats chosen
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
print("Selected item is", currentArray[row])
activeTextField.text = currentArray[row]
}