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
}
}
嘿伙计们,我怎么能在同一个单元格中显示字典键和值。
答案 0 :(得分:5)
将类型添加到数组
[String: UIImage]
并将类型element.keys
和element.values
添加到数组:数组(element.keys)和数组(element.values)
如果您未将element.keys
和element.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