使用相同的UIpickerview的多个输入字段

时间:2018-08-18 12:21:59

标签: compiler-errors uipickerview multiple-input

我在两个输入文本字段上使用相同的pickerview。但是,当我对第二个输入使用pickerview时,该应用程序始终崩溃,因为出现了索引超出范围的错误。我在pickerview中使用了“重新加载组件”,所以我一生都不知道为什么它仍然会给出该错误。一整天都在努力解决这个问题,因此我们将不胜感激!

MainVC类:UIViewController,UITextFieldDelegate,UIPickerViewDelegate,UIPickerViewDataSource {

@IBOutlet weak var fromTextField: UITextField!
@IBOutlet weak var toTextField: UITextField!

var countries = [Country]()

override func viewDidLoad() {
    super.viewDidLoad()

    //initialise data
    appendCountries()

    //set-up picker view
    let pickerView = UIPickerView()
    pickerView.delegate = self
    pickerView.dataSource = self
    fromTextField.inputView = pickerView
    toTextField.inputView = pickerView

}

//pickerview set-up
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].country
    }
    else {
        let selectedCountry = pickerView.selectedRow(inComponent: 0)
        return countries[selectedCountry].cities[row]   //error here... Thread 1: Fatal error: Index out of range
    }
}

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 country = countries[selectedCountry].country
    let city = countries[selectedCountry].cities[selectedCity]

    if fromTextField.isEditing == true {
        fromTextField.text = city
    } else {
        toTextField.text = city
    }
}

0 个答案:

没有答案