2017-08-03 69 views
0

我想根據Dictionary中的行數動態地生成單元格。在視圖加載時,字典爲空,並且在道路上被綁定。
該字典與三個鍵值很好地綁定,但是當我想根據字典值和鍵創建單元格時,總是會創建三個字典中的最後一項。tableView Swift中的乘積值

我無法弄清楚爲什麼。

這是我的代碼:

var peripherals = [String:String]() 

    override func numberOfSections(in tableView: UITableView) -> Int { 
     return 1 
    } 

override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { 
    print(peripherals.count) 
    return peripherals.count 
} 


override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { 
    let cell = tableView.dequeueReusableCell(withIdentifier: "LabelCell", for: indexPath) 

    for (peripheralDeviceUUID,peripheralDeviceName) in peripherals { 
     cell.textLabel?.text = "\(indexPath) \(peripheralDeviceName) : \(peripheralDeviceUUID)" 
    } 


    return cell 
} 

override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { 
    return "Section \(section)" 
} 
+1

只是刪除環並設置爲textLabel使用indexPath.row cell.textLabel的.text =「\(indexPath.row)\(peripheralDeviceName)?: \(peripheralDeviceUUID)「 –

+0

@Ralucalonescu你的字典中有什麼關鍵字? –

+0

你想根據你的字典中的值的單元格數量?就像你說的那樣,你的字典中有3個關鍵值,那麼你想基於數字還是按鍵來顯示單元格?或基於價值? – Pankaj

回答

2

Firt使鍵和值的陣列,從你的字典。

let dict = ["a": "first", "b": "second", "c": "third"] 
    let arrayKeys = Array(dict.keys) 
    let arrayValues = Array(dict.values) 

然後使用這些陣列在cellForRow:

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { 
      let cell = tableView.dequeueReusableCell(withIdentifier: "LabelCell", for: indexPath)  
      cell.textLabel?.text = "\(indexPath.row) \(arrayValues[indexPath.row]) : \(arrayKeys[indexPath.row])" 
      return cell 
    }