如何用字典中的数据填充UITableView.迅速 [英] How to fill UITableView with a data from Dictionary. Swift
本文介绍了如何用字典中的数据填充UITableView.迅速的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
请帮我用字典中的数据填充表格视图单元格.例如,我有这样的单元格:
Please help me with filling table view cells with data from a dictionary. For instance, I have cell like so:
,为了填充数据,我从覆盖cellForRowAt
方法开始:
and for filling it with data I've started with overriding cellForRowAt
method:
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "CurrencyCell", for: indexPath) as! CurrencyCell
for (key, value) in currencies! {
print("key is - \(key) and value is - \(value)")
}
// ?
// cell.currencyLabel.text =
// cell.askLabel.text =
// cell.bidLabel.text =
return cell
}
此处的词典打印输出:
key is - EUR and value is - Rate(ask: Optional("30.8500"), bid: Optional("30.1000"))
key is - USD and value is - Rate(ask: Optional("26.3000"), bid: Optional("26.0500"))
key is - RUB and value is - Rate(ask: Optional("0.4150"), bid: Optional("0.3750"))
如何执行此操作?预先感谢!
How to do this? Thanks in advance!
推荐答案
我使用了struct Rate来重现您当前的输出
I used a struct Rate to Reproduce your current Output
struct Rate {
var ask : Float?
var bid : Float?
static var shared = Rate()
mutating func initWithDictValues(_ currentRate : Rate) {
self.ask = currentRate.ask
self.bid = currentRate.bid
}
}
货币数组
/// Array Declaration
var currencies = [String:Any]()
/// Add Values
currencies = ["EUR":Rate(ask: 30.8500, bid: 30.8500),"USD":Rate(ask: 26.3000, bid: 26.3000),"RUB":Rate(ask: 0.4150, bid: 0.4150)]
获取单独数组中的所有键,以便我们可以轻松地使单元出队
var keysArray = Array(currencies.keys)
TableView函数
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "CurrencyCell", for: indexPath) as! CurrencyCell
/// Get CurrentKey
let currentKey = keysArray[indexPath.row]
let currentIndexKey : Rate = currencies[currentKey] as! Rate
/// Assign Values
cell.currencyLabel.text = currentKey
cell.askLabel.text = currentIndexKey.ask ?? 0
cell.bidLabel.text = currentIndexKey.bid ?? 0
return cell
}
游乐场输出
希望这会有所帮助
这篇关于如何用字典中的数据填充UITableView.迅速的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文