我是 Swift 新手!我可以在表格 View 中正确显示所有艺术家。但是,我无法弄清楚如何在从查询返回的分段艺术家列表中查找字符串(艺术家姓名)。我的代码可以在第一部分中找到任何艺术家,但不能在其他任何部分中找到。在我开始搜索下一部分之前,我的 rowNum 似乎没有重置为 0(尽管我尝试过)。示例:第 0 部分(字母 A)当前有 12 位艺术家 (0 - 11)。如果我尝试在第 1 部分(字母 B)中查找第三位艺术家(披头士乐队),我会得到正确的部分编号 1,但行号为 14(披头士乐队的 rowNum 应为 2)。
var qryArtists = MPMediaQuery.artistsQuery()
var rowNumInSectionWhereArtistWasFound = 0
var sectionNumOfSectionWhereArtistWasFound = 0
func findIndexAndSectionOfArtistInQuery(artist: String) {
var sectionNum = 0
var rowNum = 0
var found = false
// Search each section
while (sectionNum < qryArtists.itemSections?.count) && (found == false) {
// Search each row in the current section
while (rowNum < qryArtists.collectionSections![sectionNum].range.length) && (found == false) {
if qryArtists.collections![rowNum].items[0].artist == artist {
rowNumInSectionWhereArtistWasFound = rowNum
sectionNumOfSectionWhereArtistWasFound = sectionNum
found = true
}
rowNum = rowNum + 1
}
sectionNum = sectionNum + 1
rowNum = 0 // Reset the rowNum each time you start searching a new section
}
}
非常感谢您的帮助1!
最佳答案
如果您希望有一个函数来搜索您的表格 View 并返回一个 NSIndexPath
(封装行和部分的对象),这将搜索您的单元格,询问每个单元格(哪个我假设持有对其艺术家属性的引用)如果它们有匹配的名称:
func findIndexAndSectionOfArtistInQuery(artist: String) -> NSIndexPath {
for indexSection in 0...tableView.numberOfSections {
let numberOfRows = tableView.numberOfRowsInSection(indexSection)
for indexRow in 0...numberOfRows {
let indexPath: NSIndexPath = NSIndexPath(forRow: indexRow, inSection: indexSection)
let cell = tableView.cellForRowAtIndexPath(indexPath) as? CustomCell
if(cell!.artist.name == artist) {
return indexPath
}
}
}
return nil
}
如果找不到艺术家,此函数将返回nil
。
我建议您重新考虑您的方法。您应该查询模型,而不是表格 View 中的数据。此外,您应该考虑创建一个单独的类,以便以最有效的方式搜索模型。
关于ios - 在表格 View 部分的行中搜索艺术家(字符串),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39298415/