gpt4 book ai didi

ios - UITableView 无法使用 Swift 3 中的 Index 正确显示数据

转载 作者:搜寻专家 更新时间:2023-11-01 07:14:12 24 4
gpt4 key购买 nike

enter image description here我的应用程序项目中有一个 UITableView,它从数组中提取数据。此数据也必须编入索引。但由于某种原因,数据没有显示在适当的部分,即 A、B 等。我似乎看不出有什么问题。到目前为止我的数据是:

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

}
}

对此有什么想法吗?

最佳答案

一切都很好,除了:

if wordsDict[wordKey.lowercased()] != nil {
cell.textLabel?.text = university[indexPath.row]
}

我认为你犯了一个错误。让更改为:

if let wordValues = wordsDict[wordKey] {
cell.textLabel?.text = wordValues[indexPath.row]
}

这是结果: enter image description here

关于ios - UITableView 无法使用 Swift 3 中的 Index 正确显示数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43181393/

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