简体   繁体   English

uitableview部分中的特定uitableviewcell

[英]Specific uitableviewcell's in section of uitableview

I have this code for each index of my uitableview 我的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. 我有两个部分,每个部分有5行。 How can I put indexPath.row 1 thru 5 in section 1 and indexPath.row 6 thru 10 in section 2? 如何在第1部分中将indexPath.row 1到5以及第2部分中的indexPath.row 6到10中?

- (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. 现在你的表视图将需要2个部分,每个部分有5行,并尝试绘制它们。 Then, in cellForRowAtIndexPath: 然后,在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: 使用actualIndex的上述逻辑导致:

  • Section 1, Rows 1 to X returns indexPath.row unchanged 第1节,第1行至第X行返回的indexPath.row不变
  • Section 2, Rows 1 to Y returns X+indexPath.row 第2节,第1行到第Y行返回X + indexPath.row
  • Section 3, Rows 1 to Z returns X+Y+indexPath.row 第3节,第1行到第Z行返回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. 如果您有支持表格单元格的基础数组(或其他平面容器类),则可以使用这些项目在表格视图中填写多个部分。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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