简体   繁体   中英

How to populate data in a tableView as alphabetical order while using section index

I'm implementing an app where i need to show a tableView. tableView needs to have alphabetical search on the right side by clicking on any letter it needs to show data starting with that letter. I've implemented the vertical alphabet search and when user clicks on any letter it takes user to that particular section. But the problem is every section has the same data it's not populating according to alphabet.

Here is my code for this. // Here exhibitorArray contains all the info to populate data in tableView.

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return [self.exhibitorArray count];
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
        return [[[UILocalizedIndexedCollation currentCollation] sectionTitles] objectAtIndex:section];
    }

- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView {
        return [[UILocalizedIndexedCollation currentCollation] sectionIndexTitles];

    }

- (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index {
        return [[UILocalizedIndexedCollation currentCollation] sectionForSectionIndexTitleAtIndex:index];


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    // Return the number of rows in the section.
    return [self.exhibitorArray count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:nil];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];

    }
    [self.exhibitorTableView setSeparatorInset:UIEdgeInsetsMake(0, 0, 0, 0)];

    UIView* bgview = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 1, 1)];
    bgview.opaque = YES;
    bgview.backgroundColor = [UIColor colorWithRed:244.0f/255 green:245.0f/255 blue:246.0f/255 alpha:1.0];
    [cell setBackgroundView:bgview];

    UIImageView *defaultImage = [[UIImageView alloc]init];
    [defaultImage setFrame:CGRectMake(5.0f, 5.0f, 40.0f, 40.0f)];
    [cell addSubview:defaultImage];

    NSString *urlString = @"http://";
    urlString = [urlString stringByAppendingString:[NSString stringWithFormat:@"%@",[[self.exhibitorArray objectAtIndex:indexPath.row]valueForKey:@"image"]]];
    NSLog(@"%@",urlString);

    AsyncImageView *asyncImageView = [[AsyncImageView alloc] initWithFrame:CGRectMake(0.0f, 0.0f, 40.0f, 40.0f)];
    [asyncImageView setBackgroundColor:[UIColor clearColor]];
    [asyncImageView loadImageFromURL:[NSURL URLWithString:urlString]];
    [defaultImage addSubview:asyncImageView];
    defaultImage.contentMode = UIViewContentModeScaleAspectFit;
    asyncImageView = nil;
    defaultImage = nil;

    NSString *name_string = [[self.exhibitorArray objectAtIndex:indexPath.row]valueForKey:@"name"];

    UILabel *user_name = [[ UILabel alloc]init ];
    [user_name setFrame:(CGRectMake(58, 5, 270, 25))];
    [user_name setBackgroundColor: [UIColor clearColor]];
    [user_name setText:name_string];
    [user_name setFont:[UIFont fontWithName:@"Roboto-Light" size:14]];
    [user_name setTextAlignment:NSTextAlignmentLeft];
    [user_name setTextColor:[UIColor colorWithRed:93.0f/255 green:94.0f/255 blue:94.0f/255 alpha:1.0]];
    [cell addSubview:user_name];
    user_name = nil;

    [cell setAccessoryType:UITableViewCellAccessoryDisclosureIndicator];

    return cell;
}

output of this is coming something like this. 在此处输入图片说明

The following is wrong:

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    // Return the number of rows in the section.
    return [self.exhibitorArray count];
}

You have to separate your arrays for every section. Let's say a different array for letter 'A' and a different array for letter 'B' and so on. Then, based on the section index, you will get the data for the correct array.

For example you can use an array of arrays like this array[section][index] or a dictionary like this dict['A'][index] .

So the above function has to be:

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    // based on array of arrays
    return [[self.exhibitorArray objectAtIndex:indexPath.section] count];
}

and then, in your cellForRowAtIndexPath: you can use

NSString *name_string = [[[self.exhibitorArray objectAtIndex:indexPath.section] objectAtIndex:indexPath.row] valueForKey:@"name"];

Update: Convert exhibitorArray

- (void)convertArray
{
    //NSMutableArray *exhibitorArray = [[NSMutableArray alloc] initWithArray:@[@"abra", @"Catabra"]];

    NSArray *data = [exhibitorArray copy];
    exhibitorArray = [[NSMutableArray alloc] initWithCapacity:27];
    // 27 elements, 26 for A-Z plus one for '#'
    for (int i=0; i<27; i++)  
        [exhibitorArray addObject:[[NSMutableArray alloc] init]];

    int firstAsciiPos = (int)[@"A" characterAtIndex:0];
    for (int i=0; i<[data count]; i++)
    {
        int index = (int)[[[data objectAtIndex:i] uppercaseString] characterAtIndex:0] - firstAsciiPos;
        if (index < 0 || index > 25)
        {
            // it is not between A and Z, add it to '#'
            index = 26;
        }
        [[exhibitorArray objectAtIndex:index] addObject:[data objectAtIndex:i]];
    }
}

The above code converts your array to a two-dimensional array based on alphabet letters. Please feel free to change it according to your code and don't forget to handle memory deallocations if you are not using ARC.

You can use the method " sortedArrayUsingSelector ":

When you got your array filled to show your data, just after:

exhibitorArray=[exhibitorArray sortedArrayUsingSelector:@selector(localizedCaseInsensitiveCompare:)];

EDIT : Your array contains Dictionarys ? I use this on my code. Use the correct Key you want use to sort your objects. In my case is "name":

NSSortDescriptor *descriptor = [[NSSortDescriptor alloc] initWithKey:@"name" ascending:YES];    

NSArray *sortDescriptors = [NSArray arrayWithObjects:descriptor, nil]; 

exhibitorArray= [exhibitorArray sortedArrayUsingDescriptors:sortDescriptors]; 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM