How to make a table from a dictionary with multiple content types in Swift?

青春壹個敷衍的年華 提交于 2020-01-22 10:33:51

问题


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.


回答1:


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  

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
  }

}


来源:https://stackoverflow.com/questions/26453675/how-to-make-a-table-from-a-dictionary-with-multiple-content-types-in-swift

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!