我正在尝试将词典中的“专业”与与每个专业相关的图片相对应,以便其显示在单元格中。

import Foundation

class ClassRosterModel {
    var studentsRoster = [Dictionary<String, String>] ()
    init () {
        studentsRoster.append(["name": "Kaz, Alex", "number" : "s0834347", "major" : "SE"])
        studentsRoster.append(["name": "O'Rore, Ryan", "number" : "s0835357", "major" : "SE"])
        studentsRoster.append(["name": "Lote, Lote", "number" : "s0835357", "major" : "SE"])
        studentsRoster.append(["name": "Flora, Nico", "number" : "s0748324", "major" : "MA"])
    }
}

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCellWithIdentifier("studentCell", forIndexPath: indexPath)

    // Configure the cell...
    cell.textLabel?.text = studentsList[indexPath.row]["name"]
    cell.detailTextLabel?.text = studentsList[indexPath.row]["number"]
    print("Student's name: \(studentsList[indexPath.row]["name"])")
    print("Student's number: \(studentsList[indexPath.row]["number"])")

    return cell

最佳答案

您可以制作字典以将“主要”映射到图像,例如:

let images = [
    "SE": UIImage(named: "se-image.png"),
    "MD": UIImage(named: "another-image.png")
]
let major = studentsList[indexPath.row]["major"]
if let image = images[major] {
    cell.imageView?.image = image
}




我会很高兴为您服务,并为您提供一个更好的示例,说明如何编写良好的Swift代码:

enum Major: String {
    case SE
    case MA

    var image: UIImage? {
        return UIImage(named: self.rawValue)
    }
}
struct Student {
    let name: String
    let number: String
    let major: Major
}

class SomeTableViewController: UITableViewController {
    let students = [
        Student(name: "Kaz, Alex",    number: "s0834347", major: .SE),
        Student(name: "O'Rore, Ryan", number: "s0835357", major: .SE),
        Student(name: "Lote, Lote",   number: "s0835357", major: .SE),
        Student(name: "Flora, Nico",  number: "s0748324", major: .MA)
    ]

    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let student = students[indexPath.row]

        let cell = tableView.dequeueReusableCellWithIdentifier("studentCell", forIndexPath: indexPath)
        cell.textLabel?.text = student.name
        cell.detailTextLabel?.text = student.number
        cell.imageView?.image = student.major.image
        return cell
    }
}

关于swift - 访问字符串键以显示获取图像(Swift),我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/37666836/

10-12 00:16
查看更多