我使用不同的數組填充選取器視圖,具體取決於您單擊哪個文本字段。但是,無論何時我選擇「Untergrund」數組的第五行,該應用程序都會崩潰,索引超出範圍錯誤。它顯示了行int = 4和組件int = 0。錯誤發生在第一個if語句在did select行函數中設置的行中。我不知道爲什麼會這樣......使用選取器視圖時指數超出範圍錯誤
下面是相關代碼:
@IBOutlet weak var Stadt: UITextField!
@IBOutlet weak var Strasse: UITextField!
@IBOutlet weak var Platzart: UITextField!
@IBOutlet weak var Groesse: UITextField!
@IBOutlet weak var AnzToreKoerbe: UITextField!
@IBOutlet weak var Untergrund: UITextField!
// Variable für die Firebase Database
override func viewDidLoad() {
super.viewDidLoad()
Stadt.delegate = self
Untergrund.delegate = self
Groesse.delegate = self
AnzToreKoerbe.delegate = self
Platzart.delegate = self
Picker.delegate = self
}
@IBOutlet weak var Picker: UIPickerView!
var currentData = [""]
let UntergrundArray = ["Asphalt", "Kunstrasen Sand", "Kunstrasen Granulat", "Rasen", "Tartan", " "]
let StadtArray = ["Norderstedt", "Hamburg", "Berlin", "München"]
let GroesseArray = [ "2 vs 2", "3 vs 3", "4 vs 4", "5 vs 5"]
let AnzTorKoerbe = ["1", "2", "3", "4"]
let Art = ["Fußball", "Basketball"]
func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool{
if textField.tag == 1{
currentData = StadtArray
}else if textField.tag == 2{
currentData = UntergrundArray
}else if textField.tag == 3 {
currentData = GroesseArray
}else if textField.tag == 4 {
currentData = AnzTorKoerbe
}else if textField.tag == 5 {
currentData = Art
}
Picker.reloadAllComponents()
return false;
}
func numberOfComponents(in pickerView: UIPickerView) -> Int {
return 1
}
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
return currentData.count
}
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
return currentData[row]
}
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
let itemSelected = currentData[row]
print(itemSelected)
if (itemSelected == StadtArray[row]) {
Stadt.text = StadtArray[row]
}else if (itemSelected == UntergrundArray[row]) {
Untergrund.text = UntergrundArray[row]
}else if (itemSelected == GroesseArray[row]) {
Groesse.text = GroesseArray[row]
}else if (itemSelected == AnzTorKoerbe[row]) {
AnzToreKoerbe.text = AnzTorKoerbe[row]
}else {
Platzart.text = Art[row]
}
}
如果您將當前模型交換到'currentData'中,以便正確的計數總是'currentData.count','didSelectRow'中的大'if/else'的指向是什麼?當然'currentData [row]'總是所需的數據。這樣就不會有得到錯誤的模型數組和錯誤的索引值的風險。 – matt
僅供參考 - 標準的做法是將變量和方法命名爲以小寫字母開頭。類名應以大寫字母開頭。 – rmaddy
@rmaddy同意,但要理解這對於德語人來說是一個困難的慣例,他們的語言要求以大寫字母開頭。如果你懂德語,他的變量名簡直就是德語單詞,看起來完全自然。 – matt