【问题标题】:How to make a table from a dictionary with multiple content types in Swift?如何在 Swift 中从具有多种内容类型的字典中制作表格?
【发布时间】:2014-10-19 18:03:02
【问题描述】:

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

【问题讨论】:

  • 您是否已经尝试过解决此问题?如果你能表现出自己的一些努力,社区通常会更好地接受它。
  • 解析非结构化数据是目前swift中比较烦人的任务之一。看看swiftyJSON 之类的一些项目以获取想法。
  • 是的,我尝试到处搜索以找到类似问题的解决方案,但没有一个对我有用,我为此工作了 2-3 小时。我是 Swift 的初学者。

标签: xcode uitableview swift ios8 xcode6


【解决方案1】:

你必须实现 UITableViewDataSource 方法
记得将 tableView 的 dataSource 属性设置为 ViewController
比您从数组中获取一个对象(您的 NSDictionary)并使用它的数据设置单元格标签和 imageView。

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

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

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
  }

}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-16
    • 2019-03-10
    • 2016-02-22
    • 1970-01-01
    • 1970-01-01
    • 2019-03-30
    相关资源
    最近更新 更多