2014-10-19 54 views
2

我做了一個NSArray與NSDictionary對象包含從api下載的內容。我還在main.storyboard上創建了一個帶有UIImage標籤和兩個文本標籤作爲其內容的原型單元格的tableview對象。 如何將數據從數組放到表中,以便每個與我的原型樣式相同的單元格顯示數組中NSDictionary的內容。如何在Swift中使用多種內容類型的字典創建表格?

+0

有什麼,你已經試圖解決這個問題?如果你能從你身邊表現出一些努力,它通常會更好地被社區接受。 – Erik 2014-10-19 18:10:31

+0

解析非結構化數據是當前迅速比較煩人的任務之一。看看一些項目,如[swiftyJSON](https://github.com/SwiftyJSON/SwiftyJSON)的想法。 – cmyr 2014-10-19 18:15:24

+0

是的,我嘗試搜索到處尋找類似問題的解決方案,但他們都沒有爲我工作,我正在爲它工作2-3小時。我是Swift的初學者。 – 2014-10-19 18:18:30

回答

16

您必須實現UITableViewDataSource方法
記住的tableView的源屬性設置爲視圖控制器
比你從數組,並設置電池標籤和ImageView的得到一個對象(你的NSDictionary)與它的數據。

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 
    } 

} 
相關問題