Far*_*azi -1 dictionary uitableview swift
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
}
}
Run Code Online (Sandbox Code Playgroud)
嘿伙计们,我怎么能在同一个单元格中显示字典键和值.
将类型添加到数组
[String: UIImage]和类型转换,element.keys并将数组添加到element.values:Array(element.keys)和Array(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
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
492 次 |
| 最近记录: |