2017-08-03 61 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 
    }