【问题标题】:Populating a UIPIckerView with remote JSON array使用远程 JSON 数组填充 UIPIckerView
【发布时间】:2020-04-29 12:15:17
【问题描述】:

我正在从远程服务器下载 JSON 数组:

var colores = [Colores]()


func downloadJSONColores(completed: @escaping () -> ()) {
         let url = URL(string: "https://../colores.php")


         URLSession.shared.dataTask(with: url!) { (data,response,error) in

            print(data as Any)
            print(response as Any)

         if error == nil {
             do {
                 self.colores = try JSONDecoder().decode([Colores].self, from: data!)

                 DispatchQueue.main.async {
                     completed()
                 }

             }catch{

             }

         }
         }.resume()


     }

我有一个 Colores 的结构类:

struct Colores:Decodable {

    let id: Int
    let nombre: String
    let icono: String
    let modelo: Int
    let caracterista: Int

}

我需要用解码的 JSON 对象填充 PickerView,将字段名称显示为标题并存储来自 pickerview 所选项目的字段 id。

我在viewDidLoad中调用downloadJSONColores方法如下:

downloadJSONColores {
            coloresPV.reloadData()
                     }

其中coloresPV 是我的pickerView,但显然这种方式只适用于collectionViews,不适用于pickerViews。 在执行 downloadJSONColores 时填充 pickerView 的最佳方式是什么?

【问题讨论】:

    标签: ios swift uipickerview


    【解决方案1】:

    我已经解决了直接在 viewDidLoad 方法中解码 JSON 数组的问题,如下所示:

    let url = URL(string: "https://..")!
    let dataTask = URLSession.shared.dataTask(with: url) { data, _, error in
        if let error = error { print(error); return }
        do {
            let result = try JSONDecoder().decode([Colores].self, from: data!)
            print(result)
            self.colores = result.map{$0.self}
            DispatchQueue.main.async {
              self.coloresPV.reloadAllComponents()
            }
        } catch { print(error) }
    }
    dataTask.resume()
    

    【讨论】:

      【解决方案2】:

      看看UIPickerViewDataSourceUIPickerViewDelegate 协议。

      如果我正确理解您的问题,您需要在 ViewController 中保留一个变量 colors: [Colores]

      然后:

      • UIPickerViewDataSourcefunc numberOfComponents(in: UIPickerView) -> Int函数的实现中返回colors.count

      • UIPickerViewDelegate的方法pickerView(UIPickerView, titleForRow: Int, forComponent: Int) -> String?函数中返回正确的标题

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-09-28
        • 2014-02-08
        相关资源
        最近更新 更多