如何在tableview单元格中传递字典?

时间:2018-04-06 11:14:01

标签: swift uitableview dictionary

import UIKit

class ViewController: UIViewController, UITableViewDataSource,UITableViewDelegate {

    @IBOutlet weak var label: UILabel!
    @IBOutlet weak var imageView: UIImageView!
    @IBOutlet weak var tableView1: UITableView!

    let element = ["Sports": #imageLiteral(resourceName: "ios"),"Grocery":#imageLiteral(resourceName: "ios"),"Cosmetics":#imageLiteral(resourceName: "ios")]

    override func viewDidLoad() {
        super.viewDidLoad()
        tableView1.delegate = self
        tableView1.dataSource = self
        // Do any additional setup after loading the view, typically from a nib.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

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

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

        cell.textLabel?.text = element.keys

        cell.imageView?.image = element.values
        return cell
    }

}
嘿伙计们,我怎么能在同一个单元格中显示字典键和值。

2 个答案:

答案 0 :(得分:5)

  

将类型添加到数组[String: UIImage]并将类型element.keyselement.values添加到数组:

     

数组(element.keys)数组(element.values)

如果您未将element.keyselement.values类型转换为数组,则会收到Cannot subscript a value of type 'Dictionary<String, UIImage>.Keys' with an index of type 'Int

之类的错误
let element: [String: UIImage] = ["Sports": #imageLiteral(resourceName: "ios"),"Grocery":#imageLiteral(resourceName: "ios"),"Cosmetics":#imageLiteral(resourceName: "ios")]

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) ->UITableViewCell{
    let cell = tableView.dequeueReusableCell(withIdentifier: "customcell",for: indexPath)
    cell.textLabel?.text = Array(element.keys)[indexPath.row]
    cell.imageView?.image = Array(element.values)[indexPath.row]
    return cell
}

答案 1 :(得分:2)

您可以获取所有keys字典并使用indexPath.row来获取key,然后通过此value获取key

let keys = Array(element.keys)
let key = keys[indexPath.row]
cell.textLabel?.text = key
cell.imageView?.image = element[key]

建议:如果您要维护订单,则必须使用Array代替Dictionary,而Array(element.keys)将返回按升序排序的所有键订购。以下是示例:

let element = [["name": "Sports", "image": #imageLiteral(resourceName: "ios")], ["name": "Grocery", "image": #imageLiteral(resourceName: "ios")], ["name": "Cosmetics", "image": #imageLiteral(resourceName: "ios")]]
let info = element[indexPath.row]
cell.textLabel?.text = info["name"] ?? ""
cell.imageView?.image = info["image"] ?? defaultImage