Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift - how to create correct sectionForSectionIndexTitle?

I have a section index that contains full alphabet - however, sections in my table contains only a few letters (e.g. C, F, N, U).

I would like to modify sectionForSectionIndexTitle to properly show right sections when sliding finger over section index. I'm still not sure how to do it using sections.append...

Thank you for help.

This is how my code looks like:

Section.swift

struct Section
{
    var heading : String
    var items : [String]

    init(title: String, objects : [String]) {

        heading = title
        items = objects
    }
}

ViewController.swift

func updateSections(index : Int) {

    switch index {

    case 0:
        sections.append(Section(title: "C", objects: ["Czech Republic"]))
        sections.append(Section(title: "F", objects: ["France"]))
        sections.append(Section(title: "N", objects: ["Norway"]))
        sections.append(Section(title: "U", objects: ["USA"]))

    default: break
    }

    tableViewOutlet.reloadData()
}

let arrIndexSection = ["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 sectionIndexTitlesForTableView(tableView: UITableView) -> [String]? {
    if segmentedControlOutlet.selectedSegmentIndex == 0 {
        return arrIndexSection
    } else {
        return [""]
    }
}

func tableView(tableView: UITableView, sectionForSectionIndexTitle title: String, atIndex index: Int) -> Int {
    let temp = arrIndexSection as NSArray
    return temp.indexOfObject(title)
}

func numberOfSectionsInTableView(tableView: UITableView) -> Int {
    return sections.count
}

func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    let section = sections[section]
    return section.items.count
}

func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
    return sections[section].heading
}
like image 582
Heky Avatar asked Oct 30 '22 22:10

Heky


1 Answers

try following code in your project :

func tableView(tableView: UITableView, sectionForSectionIndexTitle title: String, atIndex index: Int) -> Int {
    var tempIndex:Int = 0
    for str in arrIndexSection {
        if str == title {
            return tempIndex
        }
        tempIndex += 1
    }
    return 0
}
like image 90
Steven Gardner Avatar answered Nov 10 '22 00:11

Steven Gardner