CroiSciento CroiSciento - 3 months ago 45
iOS Question

sectionForSectionIndexTitle retrieve previous section

I have a UITableView with sectionIndexTitles. Here's my data source :

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
}


The variable
sectionTitles
is a similar array to
sSectionTitles
except that it only contains section indexes that are valid. For example, if I have no Contact with their name starting with the letter D, then "D" won't be in
sectionTitles
.

I'm trying to replicate the behavior in the Contact application :


  • If the user clicks on the Index title "D" and if there is at least one contact in the B section, then scroll to this section.

  • Else, scroll to the previous section available. (In this example, if there are no contacts for the B and C letter then scroll to A)



I've been stuck of this for many hours I still don't know how I could apply this logic. I thought about using a recursive function but I didn't manage to pull this off. Does someone has any lead on how this could be achieved?

Thanks.

Answer

I think you can do it by recursion. Use another helper function to retrieve the appropriate index and call it from tableview data source function. Example,

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!
}