我试图将我的字典中的“专业”与每个专业的相关图片对应,以便显示在单元格中。
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
答案 0 :(得分:1)
你可以制作一本字典来映射你的&#34; major&#34;对于图像,例如:
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
}
}
答案 1 :(得分:0)
在您的代码中,您已声明var studentsRoster = [Dictionary<String, String>] ()
,这意味着包含键和字符串的字典数组。字符串的值。你可能想要做的第一件事就是修复它,如果你不打算将它作为一个字典数组。
基本上,[String]
是字符串数组的简写。 Array<String>
是长形式。同样,Dictionary<String, String>
是声明字典的长形式,您可以使用[String:String]
的简写
因此,您需要开始的代码很可能是var studentsRoster = [String:String]()
您可以添加新密钥并使用studentsRoster["key"] = "Value"