gpt4 book ai didi

swift - 访问字符串键以显示获取图像(Swift)

转载 作者:行者123 更新时间:2023-11-30 10:02:30 26 4
gpt4 key购买 nike

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

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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com