2014-10-27 72 views
0

我是新來的Swift,並不擅長操縱json和hash。解析json並用tableview顯示

這裏是我的JSON [網友的陣列]

[ 
{"name": "mary", "age": 24, "detail": "i love ..."}, 
{"name": "mark", "age": 28, "detail": "i love ..."} 
] 

我想先,然後顯示每個用戶的名稱及其age

,如果你點擊有姓名,年齡,它會顯示detail

我只知道如何迭代一個數組並將該值放在單元格中。

喜歡這種方式,但現在知道如何使用字典

cell.textLabel.text = self.items[indexPath.row]

我怎麼能知道哪些key我應該在每個循環中使用顯示tablecells?

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

我怎麼會知道這個時候,我應該使用name,下次我應該用age顯示我的手機?

enter image description here

+0

也許'cell.textLabel.text = self.items [indexPath.row] [ 「名稱」]年齡節目;'? – 2014-10-27 06:12:58

+0

但是如何顯示「年齡」?也許有很多用戶。邏輯看起來如此複雜 – newBike 2014-10-27 06:16:52

+0

那麼你使用''age''而不是''name''。這真的很複雜嗎? – 2014-10-27 06:35:17

回答

1

因爲你原來的JSON是一個數組,你可以分析在字典中的JSON元素,然後在你的細胞中使用它。

func parseJSONArray(jsonData: NSData) -> Array<NSDictionary>{ 
    var error: NSError? 
    var usersDictionary = NSJSONSerialization.JSONObjectWithData(jsonData, options: NSJSONReadingOptions.MutableContainers, error: &error) as Array<NSDictionary> 
    return usersDictionary 
} 

然後你就可以使用這個usersDictionary讓你的用戶信息:

cell.textlabel.text = usersDictionary[indexPath.row].valueForKey("name") 

對於關鍵決策的邏輯,你可以試試下面:

var index = indexPath.row/2; 
var key = indexPath.row%2; 

if (key == 0) { //show the name cell 
    cell.textlabel.text = usersDictionary[index].valueForKey("name") 
} else { //show the age cell 
    cell.textlabel.text = "Age " + usersDictionary[index].valueForKey("age") 
} 

細胞字體同樣的邏輯風格和顏色可以被你使用。它不是很複雜。只要確保將行數設置爲json數組大小的兩倍(每個鍵的單元格數爲1),併爲單元格選擇的方法提供適當的邏輯。

+0

嗨如何決定在每個循環中使用哪個鍵 – newBike 2014-10-27 06:53:39

+0

那麼,這取決於您的桌子設計。如果設計就像你在截圖中給出的那樣,那麼讓我知道? – 2014-10-27 08:27:05

+0

這是否回答了您的問題? – 2014-10-28 00:45:23

0

試試這個代碼,因爲名字是秀甚至細胞,在奇

var index = indexPath.row/2; 
var isAgeCell = indexPath.row%2 
if (isAgeCell == 0) { 
    cell.textLabel.text = self.items[index]["name"] 
} 
else { 
    cell.textLabel.text = self.items[index]["age"] 
} 
+0

嗨,有沒有更優雅的方式?像一次顯示2個單元格,一個用於'名稱',另一個用於'年齡' – newBike 2014-10-27 07:03:57