【发布时间】:2015-06-14 11:35:35
【问题描述】:
关于上一个问题,我询问了动物表视图项目中的代码错误,现在我完成了初始编码,但我的 UI 变得非常奇怪。它缺少每个动物名称的第一个字母和表格视图原型单元格。 例如,amel 应该是骆驼,hinoceros 应该是犀牛。 这是这里代码的错误吗?
import UIKit
class AnimalTableViewController: UITableViewController {
var animalsDict = [String: [String]] ()
var animalSelectionTitles = [String] ()
let animals = ["Bear", "Black Swan", "Buffalo", "Camel", "Cockatoo", "Dog", "Donkey", "Emu", "Giraffe", "Greater Rhea", "Hippopotamus", "Horse", "Koala", "Lion", "Llama", "Manatus", "Meerkat", "Panda", "Peacock", "Pig", "Platypus", "Polar Bear", "Rhinoceros", "Seagull", "Tasmania Devil", "Whale", "Whale Shark", "Wombat"]
func createAnimalDict() {
for animal in animals {
let animalKey = animal.substringFromIndex(advance(animal.startIndex, 1))
if var animalValues = animalsDict[animalKey] {
animalValues.append(animal)
animalsDict[animalKey] = animalValues
} else {
animalsDict[animalKey] = [animal]
}
}
animalSelectionTitles = [String] (animalsDict.keys)
animalSelectionTitles.sort({ $0 < $1})
animalSelectionTitles.sort( { (s1:String, s2:String) -> Bool in
return s1 < s2
})
}
override func viewDidLoad() {
super.viewDidLoad()
createAnimalDict()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
// Return the number of sections.
return animalSelectionTitles.count
}
override func tableView(tableView: UITableView, titleForHeaderInSection section:Int) -> String? {
// Return the number of rows in the section.
return animalSelectionTitles[section]
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! UITableViewCell
let animalKey = animalSelectionTitles[indexPath.section]
if let animalValues = animalsDict[animalKey] {
cell.textLabel?.text = animalValues[indexPath.row]
let imageFileName = animalValues[indexPath.row].lowercaseString.stringByReplacingOccurrencesOfString("", withString: "_", options: nil, range: nil)
cell.imageView?.image = UIImage(named:imageFileName)
}
return cell
}
}
【问题讨论】:
-
您是否检查过
animalsDict包含您所期望的内容?不应该是substringToIndex,而不是substringFromIndex,正如您在上一个问题的答案中所建议的那样吗?您是否在titleForHeaderInSection和cellForRowAtIndexPath中设置了断点并使用调试器 检查“错误”名称的来源?
标签: swift uitableview user-interface xcode6