How to split NSArray into UITableView sections alphabetically

后端 未结 3 949
北海茫月
北海茫月 2021-01-06 02:42

I have having trouble using an indexed table with section headers. Currently I have the indexes down the right hand side and I have the section headers showing correctly, th

3条回答
  •  失恋的感觉
    2021-01-06 03:12

    Hope that helps you, i don't know if is the best way to do, but it works =)

    NSArray *names = @[@"Ana Carolina", @"Ana carolina", @"Ana luiza", @"leonardo", @"fernanda", @"Leonardo Cavalcante"];
    
    NSMutableSet *firstCharacters = [NSMutableSet setWithCapacity:0];
    for( NSString*string in names ){
        [firstCharacters addObject:[[string substringToIndex:1] uppercaseString]];
    }
    NSArray *allLetters = [[firstCharacters allObjects] sortedArrayUsingSelector:@selector(caseInsensitiveCompare:)];
    int indexLetter = 0;
    NSMutableArray *separeNamesByLetters = [NSMutableArray new];
    
    
    
    for (NSString *letter in allLetters) {
        NSMutableDictionary*userBegeinsWith = [NSMutableDictionary new];
        [userBegeinsWith setObject:letter forKey:@"letter"];
        NSMutableArray *groupNameByLetters = [NSMutableArray new];
        NSString *compareLetter1 = [NSString stringWithFormat:@"%@", allLetters[indexLetter]];
        for (NSString*friendName in names) {
            NSString *compareLetter2 = [[friendName substringToIndex:1] uppercaseString];
    
            if ( [compareLetter1 isEqualToString:compareLetter2] ) {
                [groupNameByLetters addObject:friendName];
            }
        }
        indexLetter++;
        [userBegeinsWith setObject:groupNameByLetters forKey:@"list"];
        [separeNamesByLetters addObject: userBegeinsWith];
    }
    
    
    
    NSLog(@"%@", separeNamesByLetters);
    

    output:

     (
            {
            letter = A;
            list =         (
                "ana carolina",
                "Ana carolina",
                "Ana luiza"
            );
        },
            {
            letter = F;
            list =         (
                fernanda
            );
        },
            {
            letter = L;
            list =         (
                leonardo,
                "Leonardo Cavalcante"
    
            )
        }
    )
    

提交回复
热议问题