2017-09-26 38 views
1

在我的選取器視圖中,我希望默認行爲零。該行的值爲1.我希望除了按鈕之外能夠在視圖控制器上不觸及任何內容。我知道有類似的問題,但他們不適合我。PickerView選中默認行,但返回零,除非選取器視圖被移動

override func viewWillAppear(_ animated: Bool) { 

    self.pickerView.delegate = self 
    self.pickerView.dataSource = self 


    self.pickerView.selectRow(0, inComponent: 0, animated: true) 

     } 


func numberOfComponents(in pickerView: UIPickerView) -> Int { 
    return 1 
} 

func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? { 
    return String(numbers[row]) 
} 

func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int { 
    return numbers.count 

} 

func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) { 

    therow = pickerView.selectedRow(inComponent: 0) + 1   
} 

然後

@IBAction FUNC submitTapped(_發件人:任何){ 打印(therow) }

當我點擊提交併打印在0行中的值它是0,但如果我擺動選擇器視圖並將其放回第0行,則它會打印1.我需要能夠在選取器視圖上不觸及任何內容,並使其返回默認行的適當值。

+0

我想你應該在didSelectRow方法 –

+0

theRowIndex使用「theRowIndex =行」是未知@SaurabhPrajapati –

+0

是'didSelectRow'什麼時候只有按下按鈕纔會打電話? – Sweeper

回答

1

應該使用rowpickerview委託方法給你,所以你應該如下修改代碼:

func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) { 

    therow = numbers[row] 
    //theRowIndex = row //this is the index of row that you selected 


} 

例如,如果numbers陣列是號碼= [1,2,3,4 ],當你點擊第一行上面的代碼時,將把therow設置爲1,如果你點擊第二行,它將把therow設置爲2等等。

,如果你想使用你,那麼你可以使用如下編寫代碼:

therow = numbers[pickerView.selectedRow(inComponent: 0)] 

這會給你選擇的行數,但我認爲你不需要它上面的方法內。

現在,如果你不想碰拾取那麼我認爲你需要做的是:

@IBAction func submitTapped(_ sender: Any) { 
     therow = numbers[self.pickerView.selectedRow(inComponent: 0)] 
     print(therow) 

} 
+0

你從哪裏得到「theRowIndex」在我的程序中是未知的@ 3stud1ant3 –

+0

@MichaelR。我的appologies,我只提到它作爲一個例子,更新了答案,看看它是否可以幫助你 – 3stud1ant3

1

使用此說法,一旦你加載數據的選擇器視圖。

yourPicker.selectRow(0, inComponent:0, animated:true) 

您可以通過更改selectRow的第一個參數來更改默認選定值。

1

我認爲這種情況發生的原因是,didSelectRow以某種方式不被調用,如果您以編程方式選擇行。具體根據docs

通過當用戶在一個組件選擇一個行選擇器視圖調用。

所以你需要設置你的therow屬性之後您調用編程selectRow

self.pickerView.selectRow(0, inComponent: 0, animated: true) 
therow = 1 // <--- this line 
相關問題