Search code examples
iosuitableviewswiftnsarray

Alphabetical sections in table table view in swift


I have a list of names sorted alphabetically, and now I want display these names in a table view. I'm struggling with grouping these names for each letter.

My code looks like this:

let sections:Array<AnyObject> = ["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 usernames = [String]()

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell{
    
    let cellID = "cell"
    
    let cell: UITableViewCell = self.tv.dequeueReusableCellWithIdentifier(cellID) as UITableViewCell
    
    cell.textLabel?.text = usernames[indexPath.row]
    
return cell
}

func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int{
    
    return usernames.count
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int{
    
    return 26
}


func sectionIndexTitlesForTableView(tableView: UITableView) -> [AnyObject]!{
    
    return self.sections
}

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

func tableView(tableView: UITableView,
    titleForHeaderInSection section: Int) -> String?{
        
        return self.sections[section] as? String
}

and it all works pretty good except for the grouping which makes my table view end up like this:

enter image description here

So I know you should be able to use the filtered function in an Array, but I did not understand how to implement it.

Any suggestions on how to proceed would be appreciated.


Solution

  • You can put your arrays with names into dictionary with letter keys.

    For example

    var names = ["a": ["and", "array"], "b": ["bit", "boring"]]; // dictionary with arrays setted for letter keys
    

    then you need to access values in your dictionary in the next way

    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int{
        return names[usernames[section]].count; // maybe here is needed to convert result of names[...] to NSArray before you can access count property
    }
    
    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell{
    
        let cellID = "cell"
    
        let cell: UITableViewCell = self.tv.dequeueReusableCellWithIdentifier(cellID) as UITableViewCell
    
        cell.textLabel?.text = names[usernames[indexPath.section]][indexPath.row]; // here you access elements in arrray which is stored in names dictionary for usernames[indexPath.section] key
    
    return cell
    }