How to split NSArray into UITableView sections alphabetically

后端 未结 3 924
北海茫月
北海茫月 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"
    
            )
        }
    )
    
    0 讨论(0)
  • 2021-01-06 03:15

    Where and how are you populating _connections? You're using that array to decide the number of rows per section and to populate those rows, but _connectionsis returning the entire list. You need to split the data in _connections up alphabetically.

    For example, perhaps you could use an NSMutableArray of NSMutableArrays to group the data by letter. Since you already seem to know how to sort alphabetically, now you just need to identify the first characters of each string to group them properly. To do this, try:

    NSString *currentPrefix;
    
    // Store sortedConnections as a class variable (as you've done with _connections)
    // so you can access it to populate your table
    sortedConnections = [[NSMutableArray alloc] init];
    
    // Go through each connection (already ordered alphabetically)
    for (BRConnection *connection in _connections) {
    
        // Find the first letter of the current connection
        NSString *firstLetter = [connection.fullName substringToIndex:1];
    
        // If the last connection's prefix (stored in currentPrefix) is equal
        // to the current first letter, just add the connection to the final
        // array already in sortedConnections
        if ([currentPrefix isEqualToString:firstLetter]) {
            [[sortedConnected lastObject] addObject:connection];
        }
    
        // Else create a new array in sortedConnections to contain connections starting
        // with this current connection's letter.
        else {
            NSMutableArray *newArray = [[NSMutableArray alloc] initWithObject:connection];
            [sortedConnections addObject:newArray];
        }
    
        // To mark this latest array's prefix, set currentPrefix to contain firstLetter
        currentPrefix = firstLetter;
    }
    

    (This sort would work even if the first letters are unknown.)

    Then to get the number of rows per section, use [sortedConnections objectAtIndex:section] instead of _connections:

    - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
    {
        if (tableView == self.searchDisplayController.searchResultsTableView) {
            return [[sortedSearchResults objectAtIndex:section] count]; // hypothetically
        } else {
            return [[sortedConnections objectAtIndex:section] count];
        }
    }
    

    And to populate the table essentially do the same using [sortedConnections objectAtIndex:indexPath.section]:

    - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
    {
        UITableViewCell *cell = [self.tableView dequeueReusableCellWithIdentifier:@"ConnectionCell"];
    
        // Display connection in the table cell
        BRConnection *connection = nil;
        if (tableView == self.searchDisplayController.searchResultsTableView) {
            connection = [[sortedSearchResults objectAtIndex:indexPath.section] objectAtIndex:indexPath.row]; // hypothetically
        } else {
            connection = [[sortedConnections objectAtIndex:indexPath.section] objectAtIndex:indexPath.row];
        }
    
        cell.textLabel.text = connection.fullName;
        cell.textLabel.font = [UIFont fontWithName:@"TitilliumText25L-400wt" size:18];
        cell.detailTextLabel.text = connection.company;
        cell.detailTextLabel.font = [UIFont fontWithName:@"TitilliumText25L-400wt" size:12];
    
        return cell;
    }
    
    0 讨论(0)
  • 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];
    
    0 讨论(0)
提交回复
热议问题