【问题标题】:How do I push Json data to labels in a UITableView?如何将 Json 数据推送到 UITableView 中的标签?
【发布时间】:2016-04-22 11:02:47
【问题描述】:

我在自定义 UITableview 单元格中有 3 个标签,我正在尝试传递我从 Alamofire 的 api 获得的 json 数据,但我很难理解如何将返回的 json 推送到 tableview 中。任何帮助将不胜感激。 代码如下:

import UIKit
import Parse
import Alamofire

class LeagueTableController: UIViewController, UITableViewDataSource,     UITableViewDelegate {

override func viewDidLoad() {
    super.viewDidLoad()

    Alamofire.request(.GET, "https://api.import.io/store/connector/88c66c----9b01-6bd2bb--d/_query?input=webpage/url:----") .responseJSON { response in // 1
        print(response.request)  // original URL request
        print(response.response) // URL response
        print(response.data)     // server data
        print(response.result)   // result of response serialization

        if let JSON = response.result.value {
            print("JSON: \(JSON)")
        }
    }
}

func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return 1
}

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath)
    return cell
}


}

这样返回的json:

  {
connectorGuid = "88c66cb4-e64f-4316-9b01-6bd2bb2d762d";
connectorVersionGuid = "8aedfe43-948a-4559-b279-d3c3c28047a4";
cookies =     (
);
offset = 0;
outputProperties =     (
            {
        name = team;
        type = URL;
    },
            {
        name = played;
        type = DOUBLE;
    },
            {
        name = points;
        type = DOUBLE;
    }
);
pageUrl = "http://www.extratime.ie/leagues/2024/100/premier-division/";
results =     (
            {
        played = 9;
        "played/_source" = 9;
        points = 22;
        "points/_source" = 22;
        team = "http://www.extratime.ie/squads/17/";
        "team/_source" = "/squads/17/";
        "team/_text" = Dundalk;
    },
            {
        played = 9;
        "played/_source" = 9;
        points = 20;
        "points/_source" = 20;
        team = "http://www.extratime.ie/squads/7/";
        "team/_source" = "/squads/7/";
        "team/_text" = "Derry City";
    },
            {
        played = 9;
        "played/_source" = 9;
        points = 17;
        "points/_source" = 17;
        team = "http://www.extratime.ie/squads/100504/";
        "team/_source" = "/squads/100504/";
        "team/_text" = "Galway United FC";
    },
            {
        played = 9;
        "played/_source" = 9;
        points = 16;
        "points/_source" = 16;
        team = "http://www.extratime.ie/squads/29/";
        "team/_source" = "/squads/29/";
        "team/_text" = "St. Patrick's Ath";
    },
            {
        played = 8;
        "played/_source" = 8;
        points = 15;
        "points/_source" = 15;
        team = "http://www.extratime.ie/squads/30/";
        "team/_source" = "/squads/30/";
        "team/_text" = "Cork City";
    },
            {
        played = 8;
        "played/_source" = 8;
        points = 15;
        "points/_source" = 15;
        team = "http://www.extratime.ie/squads/3/";
        "team/_source" = "/squads/3/";
        "team/_text" = "Shamrock Rovers";
    },
            {
        played = 9;
        "played/_source" = 9;
        points = 10;
        "points/_source" = 10;
        team = "http://www.extratime.ie/squads/13/";
        "team/_source" = "/squads/13/";
        "team/_text" = "Finn Harps";
    },
            {
        played = 9;
        "played/_source" = 9;
        points = 10;
        "points/_source" = 10;
        team = "http://www.extratime.ie/squads/2/";
        "team/_source" = "/squads/2/";
        "team/_text" = Bohemians;
    },
            {
        played = 9;
        "played/_source" = 9;
        points = 7;
        "points/_source" = 7;
        team = "http://www.extratime.ie/squads/8/";
        "team/_source" = "/squads/8/";
        "team/_text" = "Sligo Rovers";
    },
            {
        played = 9;
        "played/_source" = 9;
        points = 7;
        "points/_source" = 7;
        team = "http://www.extratime.ie/squads/6/";
        "team/_source" = "/squads/6/";
        "team/_text" = "Bray Wanderers";
    },
            {
        played = 9;
        "played/_source" = 9;
        points = 5;
        "points/_source" = 5;
        team = "http://www.extratime.ie/squads/109/";
        "team/_source" = "/squads/109/";
        "team/_text" = "Wexford Youths";
    },
            {
        played = 9;
        "played/_source" = 9;
        points = 5;
        "points/_source" = 5;
        team = "http://www.extratime.ie/squads/15/";
        "team/_source" = "/squads/15/";
        "team/_text" = "Longford Town";
    }
);

} 我正在尝试将“played”、“points”和“team/_text”结果推送到每个标签。

【问题讨论】:

    标签: ios json swift uitableview alamofire


    【解决方案1】:

    由于问题范围很广,这里没有具体说明问题是什么,一般的步骤是:

    1) 将您的 json 映射到字典/nsdictionary。假设您发布的 JSON sn-p 是一段 JSONArray,格式如下 [{}],您只需:

    var arrayOfDictionaries:NSArray = NSJSONSerialization.JSONObjectWithData(yourData, options: nil, error: nil) as! NSArray
    

    yourData 变量是从网络下载的转换为 NSData 格式的数据

    2) 在您的自定义 tableViewCell 中为这三个标签创建出口

    3) 对于每个单元格,在里面设置这些标签

    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath)

    方法如下:

    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
      let cell:YourCustomCell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as YourCustomCell
      cell.firstLabel.text = yourDictionary["played"]
      cell.secondLabel.text = yourDictionary["points"]
      cell.thirdLabel.text = yourDictionary["team"]
      return cell
    }
    

    4) 我想您将需要更多的单元格而不是一个,然后将许多字典存储在数组中并像这样访问每个元素:

    cell.firstLabel.text = arrayOfDictionaries[indexPath.row]["played"]
    

    【讨论】:

    • 觉得可以,试试看
    • 好的,请回来提供反馈,如果您觉得有帮助,请接受答案
    • yourData 将您下载的数据,在这种情况下 response.data 作为 NSData,后者进入 func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath),正如我在回答中所说的
    • 声明一个名为 myData:NSData 的类变量,然后在视图中确实加载了 response.data 并在序列化 json 的函数中使用它。你需要自己努力解决这个问题。我真的发布了你需要知道的一切来完成它。请多一些耐心,自己尝试,因为很难重现整个问题
    • 是的,我完全理解这一点,无需抱歉,但我鼓励您在此线程之外进行更广泛的搜索,例如“未解析的标识符 ios 是什么意思”等。我希望您明白我的意思 :)
    【解决方案2】:

    您需要创建UITableViewCell 的子类,例如MyTableViewCell 并添加一个名为JSON 的属性。

    现在,由于您可能正在使用 Interface Builder 来定义您的单元格及其重用标识符(“Cell”),请将该单元格的类设置为您新创建的 MyTableViewCell 并将标签连接到您新创建的 IBOutlets定义类。

    然后,当您调用“dequeueReusableCellWithIdentifier”时,将单元格转换为 MyTableViewCell 并将其 JSON 属性设置为您希望在单元格中具有的值。 您可能希望对更改做出反应,因此添加 didSet 属性观察器。

    var JSON:[String: AnyObject] = [String: AnyObject]() {
        didSet {
            print("populate your labels with your new data");
        }
    }
    

    【讨论】:

      【解决方案3】:

      首先,您应该创建一个模型,其中包含要保存的 3 个属性,例如:

          class Data {
          var team = ""
          var point = 0
          var teamText = ""
      
          init(fromJSON json: NSDictionary) {
              team = json["team"] as! String
              point = json["points"] as! Int
              teamText = json["team/_text"] as! String
          }
      }
      

      在您的 LeagueTableController 中,创建一个数组来保存数据并将其显示给 tableView:

      var data = [Data]()
      

      配置tableView来显示数据:

      func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
          return data.count
      }
      
      func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
          let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! YourCustomCell
          let row = indexPath.row
          cell.lblA.text = data[row].team
          cell.lblB.text = "\(data[row].point)"
          cell.lblC.text = data[row].teamText
          return cell
      }
      

      最后,将您的响应 json 解析为我们的数据数组以显示到 tableView 上

      @IBOutlet weak var tableView: UITableView!
      var data = [Data]()
      
      override func viewDidLoad() {
          super.viewDidLoad()
      
          Alamofire.request(.GET, "https://api.import.io/store/connector/88c66c----9b01-6bd2bb--d/_query?input=webpage/url:----") .responseJSON { response in // 1
              print(response.request)  // original URL request
              print(response.response) // URL response
              print(response.data)     // server data
              print(response.result)   // result of response serialization
      
              if let JSON = response.result.value {
                  print("JSON: \(JSON)")
                  // parse JSON to get array of data
                  let array = JSON["results"] as! [NSDictionary]
                  // map an item to a data object, and add to our data array
                  for item in array {
                      self.data.append(Data(fromJSON: item))
                  }
                  // after mapping, reload the tableView
                  self.tableView.reloadData()
              }
          }
      }
      

      希望对您有所帮助!

      【讨论】:

      • 你可以在这里发布你的响应 JSON 吗?
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-03-31
      • 1970-01-01
      • 1970-01-01
      • 2012-08-16
      • 1970-01-01
      相关资源
      最近更新 更多