2017-03-19 72 views
2

PikerView在我的視圖控制器中沒有顯示數據。pickerview不顯示來自數組的數據

它工作正常,當我用一些數組字面值測試它。

我應該重新加載數據的地方嗎?

class FirstViewController: UIViewController, UIPickerViewDelegate, UIPickerViewDataSource 
{ 
    @IBOutlet var baseCurrency: UITextField! 
    @IBOutlet var excahngeCurrency: UITextField! 
    @IBOutlet var dropDown: UIPickerView! 

    var list: [String: AnyObject] = [String: AnyObject]() 
    var titles: [String] = [] 
    override func viewDidLoad() 
    { 
     super.viewDidLoad() 

     let url:URL = URL(string: "https://openexchangerates.org/api/currencies.json?app_id=7486951aeb994599a08cd7979bef3c03")! 
    Alamofire.request(url).responseJSON(completionHandler: 
     { 
      response in 
      switch response.result 
      { 
      case.success: 
       self.list = response.result.value as! [String: AnyObject] 
       for (key, _) in self.list 
       { 
        self.titles += [key] 
       } 

       print(self.titles) 
      case.failure: 
       print("error") 
      } 
     }) 
    } 

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

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

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

    func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) 
    { 
     exchangeCurrency.text = self.titles[row] 
    } 
} 

回答

0

前提是你從URL獲取數據(我沒有驗證這一點,我相信你確實看到你有print聲明中的數據),你需要調用reloadAllComponents您pickerview爲它重新加載數據獲取後的數據。

0

更新您的success塊爲:

case success: 

    self.list = reponse.result.value as! [String: AnyObject] 

    for (key, _) in self.list { 
     self.titles += [key] 
    } 

    print(self.titles) 

    if (self.titles.count > 0) { 
     // reload your picker view 
     self.dropDown.reloadAllComponents() 
    } else { 
     print("there is no data for your picker view") 
    } 
+0

謝謝Krunal。當我添加它,我得到以下錯誤:模糊引用成員'pickerView(_:titleForRow:forComponent :)' –

+0

你可以分享確切的錯誤行...你在這裏使用自己的選擇器視圖實例... dropDown。我想你只是複製我的代碼,並用自己的代碼替換它。您可能沒有更新選擇器實例。我已經更新了我的答案。如果您尚未更新選擇器實例,請再試一次。 – Krunal

+0

像魅力一樣工作。萬分感謝! –