如何在UITableViewCell中迭代字典值词典?

时间:2016-04-22 22:01:39

标签: ios swift

这是我的第一篇文章,我希望这是一个很好的问题,因为我已经坚持了几天。 (从字面上搜索每个相关问题,发现我无法为解决方案添加任何内容。)

基本上我正在构建一个纯粹的Swift应用程序。我的问题是我无法弄清楚如何将每个字典值放入创建的每个UITableCell中。

来自JSON的{​​{1}}响应也会创建 GET 类型。

UITableViewCell属性

  • UILabel - 持有优惠"名称"
  • UI标签#2 - 保留优惠"说明"
  • UIImage - 持有优惠" thumb_url"

所以基本上我需要在NSCFDictionary创建的每个offer中存储每个(name, description, thumb_url)对象的UITableViewCell

ViewController

GET Request

import UIKit class freeIAPCell: UITableViewCell { @IBOutlet weak var aName: UILabel! @IBOutlet weak var aDescription: UILabel! @IBOutlet weak var aImage: UIImageView! } class FreeIAPViewController: UIViewController, UITableViewDelegate, UITableViewDataSource { // Everbadge Request var apiURL = "apiurlhere" var parsedArray: [[String:String]] = [] func queryEB() { // Query DB Here // Store the API url in a NSURL Object let nsURL = NSURL(string: apiURL) let request = NSMutableURLRequest(URL: nsURL!) request.HTTPMethod = "GET" // Execute HTTP Request let task = NSURLSession.sharedSession().dataTaskWithURL(nsURL!) { data, response, error in if error != nil { print("Error = \(error)") return } let responseString = NSString(data: data!, encoding: NSUTF8StringEncoding) do { let json = try NSJSONSerialization.JSONObjectWithData(data!, options: .AllowFragments) as! NSDictionary print(json.isKindOfClass(NSDictionary)) // true let data = json.objectForKey("data") as! NSDictionary //print(data) let m = data.objectForKey("offers") as! NSArray print(m) print(m.valueForKeyPath("name")) self.parsedArray = m as! [[String : String]] } catch { print("THERE WAS AN ERROR PARSING JSON FOR EVERBADGE") } } task.resume() } override func viewDidLoad() { super.viewDidLoad() queryEB() } override func viewWillAppear(animated: Bool) { super.viewWillAppear(true) } // MARK: UITableView method implementation func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 4 } func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { return 100 } func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("freeAppCell", forIndexPath: indexPath) as! freeIAPCell let obj = parsedArray[indexPath.row] // fatal error: Index out of range cell.aName.text = obj["name"] return cell } } (print(m))

API Request Data Structure

1 个答案:

答案 0 :(得分:1)

首先为3个项目创建公共数组...

var nameArray = [String]()
var descriptionArray = [String]()
var thumbnailArray = [String]()

然后像这样循环你的json解析......

 let responseString = NSString(data: data!, encoding: NSUTF8StringEncoding) as! NSDictionary
    if responseString != nil
    {
        let items: AnyObject! = responseString["items"] as AnyObject!
        if items != nil
        {
            // Loop through all search results and keep just the necessary data.
            for var i=0; i<items.count; ++i
            {

                if let names = items[i]["name"] as? NSDictionary
                {
                    let name = names as! String
                    self.nameArray.append(name)
                }
                if let descriptions = items[i]["description"] as? NSDictionary
                {
                    let description = descriptions as! String
                    self.descriptionArray.append(description)
                }
                if let thumbnails = items[i]["thumb_url"] as? NSDictionary
                {
                    let thumbnail = thumbnails as! String
                    self.thumbnailArray.append(thumbnail)
                }
            }
        }
        self.resultsTableView.reloadData()

使用nameLabel创建一个OfferTableViewCell类:UILabel,descriptionLabel:UILabel和thumbnailImage:UIImage。最后在你的cellForRowAtIndexPath .....

 func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
    {
        let cell = tableView.dequeueReusableCellWithIdentifier("offer", forIndexPath: indexPath) as! OfferTableViewCell
        cell.nameLabel.text = self.nameArray[indexPath.row]
        cell.descriptionLabel.text = self.descriptionArray[indexPath.row]
        let url = NSURL(string: self.thumbnailArray[indexPath.row])
        let data = NSData(contentsOfURL: url!)
        cell.thumbnailImage.image = UIImage(data: data!)

        return cell

    }