gpt4 book ai didi

ios - sectionForSectionIndexTitle 检索上一节

转载 作者:行者123 更新时间:2023-11-28 16:16:17 25 4
gpt4 key购买 nike

我有一个带有 sectionIndexTitles 的 UITableView。这是我的数据源:

let sSectionTitles = ["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","#"]
var sectionTitles = [String]()

func sectionIndexTitlesForTableView(tableView: UITableView) -> [String]? {
return sSectionTitles
}

func tableView(tableView: UITableView, sectionForSectionIndexTitle title: String, atIndex index: Int) -> Int {
var section = 0
if let selectedSection = sectionTitles.indexOf(title) {
section = selectedSection
} else {
section = index
}
return section
}

变量 sectionTitles 是一个类似于 sSectionTitles 的数组,只是它只包含有效的节索引。例如,如果我没有姓名以字母 D 开头的联系人,那么“D”将不会出现在 sectionTitles 中。

我正在尝试复制联系人应用程序中的行为:

  • 如果用户点击索引标题“D”并且 B 部分中至少有一个联系人,则滚动到此部分。
  • 否则,滚动到上一个可用部分。 (在这个例子中,如果 B 和 C 字母没有联系人,则滚动到 A)

我已经坚持了好几个小时了,我仍然不知道如何应用这个逻辑。我考虑过使用递归函数,但我没能成功。有人知道如何实现这一点吗?

谢谢。

最佳答案

我认为你可以通过递归来完成。使用另一个辅助函数来检索适当的索引并从 tableview 数据源函数中调用它。例子,

func tableView(tableView: UITableView, sectionForSectionIndexTitle title: String, atIndex index: Int) -> Int {
var section = getSectionIndex(title)
return section
}

//recursive function to get section index
func getSectionIndex(title: String) -> Int {
let tmpIndex = sectionTitles.indexOf(title)
let mainIndex = sSectionTitles.indexOf(title)
if mainIndex == 0 {
return 0
}
if tmpIndex == nil {
let newTitle = sSectionTitles[mainIndex!-1]
return getSectionIndex(newTitle)
}
return tmpIndex!
}

关于ios - sectionForSectionIndexTitle 检索上一节,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39034352/

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