简体   繁体   中英

Specific uitableviewcell's in section of uitableview

I have this code for each index of my uitableview

 if (indexPath.row == 6){
        UIImageView *blog = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"blog.png"]];
        [cell setBackgroundView:blog];
        UIImageView *selectedblog = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"blogSel.png"]];
        cell.selectedBackgroundView=selectedblog;
        cell.backgroundColor = [UIColor clearColor];
        [[cell textLabel] setTextColor:[UIColor whiteColor]];
        return cell;}

and I have two sections, with 5 rows in each section. How can I put indexPath.row 1 thru 5 in section 1 and indexPath.row 6 thru 10 in section 2?

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 5;
}

Now your table view will expect 2 sections with 5 rows each, and try to draw them. Then, in cellForRowAtIndexPath:

- (UITableViewCell *)tableView:(UITableView *)tableView
         cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSUInteger actualIndex = indexPath.row;
    for(int i = 1; i < indexPath.section; ++i)
    {
        actualIndex += [self tableView:tableView 
                               numberOfRowsInSection:i];
    }

    // you can use the below switch statement to return
    // different styled cells depending on the section
    switch(indexPath.section)
    {
         case 1: // prepare and return cell as normal
         default:
             break;

         case 2: // return alternative cell type
             break;
    }
}

The above logic with actualIndex leads to:

  • Section 1, Rows 1 to X returns indexPath.row unchanged
  • Section 2, Rows 1 to Y returns X+indexPath.row
  • Section 3, Rows 1 to Z returns X+Y+indexPath.row
  • Scalable to any number of sections

If you have an underlying array (or other flat container class) of items backing your table cells, this will allow you to fill out multiple sections in the table view using those items.

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