如何在Swift中使用多种内容类型的字典制作表格? [英] How to make a table from a dictionary with multiple content types in Swift?

查看:151
本文介绍了如何在Swift中使用多种内容类型的字典制作表格?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用NSDictionary对象制作了一个NSArray,其中包含从api下载的内容。我还在main.storyboard上创建了一个tableview对象,其中一个原型单元格带有UIImage标签,两个文本标签作为其内容。
如何将数据从数组放到表中,以便每个与我的原型具有相同样式的单元格显示数组中的NSDictionary内容。

I have made an NSArray with NSDictionary objects containing contents downloaded from an api. I also made a tableview object on main.storyboard with a prototype cell with a UIImage label and two text labels as its contents. How can I put the data from array to table so that each cell with same style as my prototype shows contents of NSDictionary from the array.

推荐答案

你必须实现UITableViewDataSource方法

记得将tableView的dataSource属性设置为ViewController

比从数组和set cell获取一个对象(你的NSDictionary)标签和imageView与它的数据。

You have to implement UITableViewDataSource methods
Remember to set dataSource property of tableView to ViewController
Than you get one object(your NSDictionary) from array and set cell labels and imageView with it's data.

func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath:NSIndexPath) -> UITableViewCell  

以下是 Swift 中的完整代码示例。 Objective-C非常相似

Here is full Code example in Swift. Objective-C is very similar

class MasterViewController: UITableViewController {

   var objects = [
    ["name" : "Item 1", "image": "image1.png"],
    ["name" : "Item 2", "image": "image2.png"],
    ["name" : "Item 3", "image": "image3.png"]]

  override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return objects.count
  }

  override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

    let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as UITableViewCell

    let object = objects[indexPath.row]

    cell.textLabel?.text =  object["name"]!
    cell.imageView?.image = UIImage(named: object["image"]!)
    cell.otherLabel?.text =  object["otherProperty"]!

    return cell
  }

}

这篇关于如何在Swift中使用多种内容类型的字典制作表格?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆