我希望根据字典中的行数动态地生成单元格。在视图加载时,字典为null,并在路上绑定。
字典被三个键值很好地绑定,但是当我想要根据字典值创建单元格时,键总是创建三行,并在字典中的最后一个项。
我搞不懂为什么。
这是我的密码:
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)"
}发布于 2017-08-03 08:51:21
从字典中生成键和值数组。
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
}https://stackoverflow.com/questions/45478797
复制相似问题