具体的uitableviewcell在uitableview的部分

时间:2011-10-28 01:04:48

标签: objective-c uitableview nsindexpath

我的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;}

我有两个部分,每个部分有5行。如何在第1部分中将indexPath.row 1到5以及第2部分中的indexPath.row 6到10放入?

1 个答案:

答案 0 :(得分:3)

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

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

现在你的表视图将需要2个部分,每个部分有5行,并尝试绘制它们。然后,在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;
    }
}

actualIndex的上述逻辑导致:

  • 第1节,第1行到第X行返回indexPath.row不变
  • 第2节,第1行到第Y行返回X + indexPath.row
  • 第3节,第1行至第Z行返回X + Y + indexPath.row
  • 可扩展到任意数量的部分

如果您有支持表格单元格的基础数组(或其他扁平容器类),则可以使用这些项目在表格视图中填写多个部分。