我的 iOS 项目中有这个数据结构,它有一个从 sqlite3 数据库填充的 tableView。
struct Song {
let id: Int
let songTitle: String
let movieName: String
let songSinger: String
let musicDirector: String
let songLyrics: String
let movieReleased: String
let songScale: String
let leadCast: String
let songTrivia: String
let scaleURL: String
let youtubeURL: String
let lyricsURL: String
}
这就是我创建 sectionIndexTitlesArray 的方式:
var movieSet = Set<String>()
for song in songList {
movieSet.insert(song.movieName)
let firstLetter = String(song.movieName.prefix(1))
if !firstLetters.contains(firstLetter) {
firstLetters.append(firstLetter)
}
uniqueMovies = Array(movieSet)
uniqueMovies.sort()
sectionIndexTitles = firstLetters.sorted()
}
这就是我创建多个部分的方式:
func numberOfSections(in tableView: UITableView) -> Int {
if isSearching == true {
return 1
} else {
return uniqueMovies.count
}
}
这是节中行数的函数
if isSearching == true {
return filteredSongs.count
} else {
if sortField == "movieName"
let sectionTitle = uniqueMovies[section]
let sectionData = songList.filter { $0.movieName == sectionTitle }
return sectionData.count
}
这是 titleForHeaderSection 的函数
func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
if isSearching == true {
return nil
} else {
return " "+uniqueMovies[section]
}
}
这是 sectionIndexTitles 的函数
func sectionIndexTitles(for tableView: UITableView) -> [String]? {
if isSearching == true {
return nil
} else {
return sectionIndexTitles
}
}
这是 sectionForSectionIndexTitles 的函数
func sectionForSectionIndexTitle(title: String, atIndex index: Int) -> Int {
return sectionIndexTitles.firstIndex(of: title)!
}
问题是,当我点击右侧索引标题中的字母时,它不会跳转到相应的部分。相反,它跳转到与 sectionTitles 索引匹配的部分。例如如果我点击“D”,它会跳转到第 4 节标题。怎么了?