Search code examples
iostableviewalphabeticalsectionsdivide

divided into sections alphabetic my Tableview


i have an array that contains name in string format (es.luca,marco,giuseppe,..). This array will be used to fill the table. how can I divide the table into sections (az) and put in the name of the array inside the right section?


Solution

  • You can iterate through the array to create a dictionary with the first letter as the key and an array of names as a value:

    In Swift

    var nameDictionary: Dictionary<String, Array<String>> = [:]
    
    for name in nameArray {
        var key = name[0].uppercaseString // first letter of the name is the key
        if let arrayForLetter = nameDictionary[key] { // if the key already exists
            arrayForLetter.append(name) // we update the value
            nameDictionary.updateValue(arrayForLetter, forKey: key) // and we pass it to the dictionary
        } else { // if the key doesn't already exists in our dictionary
            nameDictionary.updateValue([name], forKey: key) // we create an array with the name and add it to the dictionary
        }
    }
    

    In Obj-C

    NSMutableDictionary *nameDictionary = [[NSMutableDictionary alloc] init];
    
    for name in nameArray {
    
        NSString *key =  [[name substringToIndex: 1] uppercaseString];
    
        if [nameDictionary objectForKey:key] != nil {
    
             NSMutableArray *tempArray = [nameDictionary objectForKey:key];
            [tempArray addObject: name];
            [nameDictionary setObject:tempArray forkey:key];
        } else {
            NSMutableArray *tempArray = [[NSMutableArray alloc] initWithObjects: name, nil];
            [nameDictionary setObject:tempArray forkey:key];
        }
    }
    

    then you can get your number of sections by using nameDictionary.count, the number of rows by getting nameDictionary[key].count and the content of your rows in a particular section with nameDictionary[key] which will return an array of all the names starting with the letter stored in key

    EDIT: couple that with Piterwilson answer to have a full answer

    EDIT 2: added Obj-C code

    Notice: As I'm not on my mac, there might be small errors in the code but the principle remains the same