pickerView无法加载在同一视图控制器中获取的数据(swift)

时间:2016-02-10 12:51:30

标签: ios swift uipickerview datamodel

我的pickerview无法从同一视图控制器中获取的数组加载数据。但是如果我将fetchHistory放在另一个viewController中(在historyViewController之前)并通过导航发送数据,那么pickerView会显示confirms数据。当我将fetchHistory放入historyViewController时,如何使它工作?或任何建议放置fetchHistory的最佳方法,而不是把它放在随机的viewController中?

historyViewController

var confirms = [DataWaitingConfirm]() //pickerView DataSource
override func viewDidLoad() {
    super.viewDidLoad()

    fetchHistory()//fetch data from server for 'confirms'
}

fetchData

func fetchHistory(){

    let headers = ["Authorization" : "\(TokenType!) \(Token!)"]
    Alamofire.request(.GET, "http://xxxx/history/", headers: headers, encoding: .JSON).responseJSON { response in
              switch response.result {
                  case .Success:
                     if let value = response.result.value {
                         let json = JSON(value)
                         print(json)
                         for (results,subJson):(String, JSON) in json["results"] {
                         print(subJson["status"].int)
                         if subJson["status"].intValue == 3 {
                             print("ada 3")
                             let orderReference = subJson["px_reference"].stringValue
                             let date = subJson["invoice_date_str"].stringValue
                             let totalPaid = subJson["total_paid"].stringValue

                             let orderPicker = "\(orderReference) \(date) \(totalPaid)"
                             let confirm = DataWaitingConfirm(orderReference: orderReference, pickerConfirm: orderPicker)
                             self.confirms += [confirm]
                                            }
                                        }}

            }
        case .Failure(let error):
            spinningActivity.hide(true)
            print(error)
            self.displayAlertMessage("could not fetch history")
        }
    }
}

挑选查看代表

func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {

    let orderToConfirm = confirms[row]
    return orderToConfirm.pickerConfirm
}

func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {


    return confirms.count
}

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

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

}

2 个答案:

答案 0 :(得分:2)

您需要致电self.pickerView.reloadAllComponents()以触发刷新。然后将再次调用数据源方法,更新的数据将显示在选择器视图中。

您的Alamofire请求以异步方式返回,因此您应在self.confirms += confirm之后触发重新加载。

注意:您也可以考虑使用dispatch_async(dispatch_get_main_queue(), {...})

在主线程上触发它

答案 1 :(得分:0)

你应该在ws回复之后使用:

reloadComponent:

reloadAllComponents: