簡體   English   中英

如何在Swift中使用多種內容類型的字典制作表格?

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

我用NSDictionary對象創建了一個NSArray,其中包含從api下載的內容。 我還在main.storyboard上創建了一個tableview對象,其中一個原型單元格帶有UIImage標簽,兩個文本標簽作為其內容。 如何將數據從數組放到表中,以便每個與我的原型具有相同樣式的單元格顯示來自數組的NSDictionary的內容。

您必須實現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
  }

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM