How to split NSArray into UITableView sections alphabetically

后端 未结 3 928
北海茫月
北海茫月 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:29

    Just in case you have custom objects , little modification in @Leo

    NSMutableSet *firstCharacters = [NSMutableSet setWithCapacity:0];
            for( ETUser *user in self.follwings){
                [firstCharacters addObject:[[user.name 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 (ETUser *user in self.follwings) {
    
                    NSString *compareLetter2 = [[user.name substringToIndex:1] uppercaseString];
    
                    if ( [compareLetter1 isEqualToString:compareLetter2] ) {
    
                        [groupNameByLetters addObject:user];
                    }
                }
                indexLetter++;
                [userBegeinsWith setObject:groupNameByLetters forKey:@"list"];
                [separeNamesByLetters addObject: userBegeinsWith];
            }
    
            self.follwings = [[NSMutableArray alloc]initWithArray:separeNamesByLetters];
    

提交回复
热议问题