Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.3k views
in Technique[技术] by (71.8m points)

ios - How to fill UITableView with a data from Dictionary. Swift

Please help me with filling table view cells with data from a dictionary. For instance, I have cell like so:

enter image description here

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
}

Printout of Dictionary here:

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!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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
    }
}

Currencies Array

/// 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)]

Get All Keys in Separate Array so we can Dequeue cell Easily

var keysArray = Array(currencies.keys)

TableView Function

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
}

Playground Output

enter image description here

Hope this helps


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...