2016-11-14 60 views
0

我有兩個UIPickerViewspickerOnepickerTwopickerTwo的內容取決於在pickerOne中選擇的內容。每個選擇器的選定項目的名稱顯示在UITextField中。UIPickerView等待didSelect,直到滾動動畫完成

的依賴性的一個例子:

如果pickerOne選擇x,然後pickerTwo將顯示element1element2,和element3

如果pickerOne選擇y,然後pickerTwo將顯示element4element5,和element6

我用下面的代碼來做到這一點:

func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) { 
    if pickerView === pickerOne { 
     textFieldOne.text = pickerOneData[row].name 

     pickerTwoData = // Update the data. 
     pickerTwo.selectRow(0, inComponent: 0, animated: false) 
    } 
    else if pickerView === pickerTwo { 
     textFieldTwo.text = pickerTwoData[row].name 
    } 
} 


func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? { 
    if pickerView === pickerOne { 
     return pickerOneData[row].name 
    } 
    else if pickerView === pickerTwo { 
     return pickerTwoData[row].name 
    } 
} 

現在我的問題是,這些採摘行事非常古怪,如果我在pickerOne選擇一排,其存在pickerTwo只有一行。

如果我選擇在pickerOne的行已在pickerTwo幾行,然後在pickerOne其中只有在pickerTwo一行選擇行。然後根據我接下來做什麼,我可以得到一個index out of range錯誤。

如果我關閉UIPickerViewself.view.endEditing(true)),那麼不存在任何問題,但如果我只是在pickerOne選擇行其在pickerTwo錯誤發生只有一行。

我懷疑這與在UIPickerView上滑動時播放的動畫有關,因爲它不會更新文本字段,直到它停止滾動爲止。

如果有人能指出我正確的方向,我真的很感激。

回答

0

我設法修復了這個錯誤,但我仍然很困惑。我改變了代碼titleForRow因此現在說:

func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? { 
    if pickerView === pickerOne { 
     let name = pickerOneData[row].name 
     return name 
    } 
    else if pickerView === pickerTwo { 
     return pickerTwoData[row].name 
    } 
} 

所有我改變是在一個變量先救名字,那麼它的工作。