我的應用程序項目中有一個UITableView,它從數組中提取數據。此數據也必須編入索引。但由於某些原因,數據不會顯示在適當的部分,即A,B等。我似乎無法看到什麼是錯的。我的數據到目前爲止是:UITableView無法正確顯示索引在Swift 3中的數據
import Foundation
import UIKit
class uniVC: UITableViewController {
let university = ["Allcat University", "Allday University", "Bejnamin University", "Cat University"]
var universitySections = [String]()
var wordsDict = [String:[String]]()
let wordIndexTitles = ["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"]
func generateWordsDict() {
for word in university {
let key = "\(word[word.startIndex])"
let lower = key.lowercased()
if var wordValues = wordsDict[lower] {
wordValues.append(word)
wordsDict[lower] = wordValues
} else {
wordsDict[lower] = [word]
}
}
universitySections = [String](wordsDict.keys)
universitySections = universitySections.sorted()
}
override func viewDidLoad() {
super.viewDidLoad()
generateWordsDict()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
//Dispose
}
// Mark table view data source
override func numberOfSections(in tableView: UITableView) -> Int {
return universitySections.count
}
override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return universitySections[section]
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
let wordKey = universitySections[section]
if let wordValues = wordsDict[wordKey] {
return wordValues.count
}
return 0
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
let wordKey = universitySections[indexPath.section]
if wordsDict[wordKey.lowercased()] != nil {
cell.textLabel?.text = university[indexPath.row]
}
return cell
}
override func sectionIndexTitles(for tableView: UITableView) -> [String]? {
return wordIndexTitles
}
override func tableView(_ tableView: UITableView, sectionForSectionIndexTitle title: String, at index: Int) -> Int {
guard let index = universitySections.index(of: title) else {
return -1
}
return index
}
}
對此問題的任何建議?
我不明白你的問題。目前的產出是多少?預期的產出是多少?不要讓人猜測問題是什麼。另外,您是否使用了斷點和調試器來遍歷代碼以查找邏輯中的錯誤? –
我不是讓人猜測問題是什麼,閱讀問題 - 數據不顯示在適當的部分,即一個不顯示在等... – Sole
截圖添加到幫助 – Sole