1

我的 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 行。如何将 indexPath.row 1 到 5 放在第 1 节中,将 indexPath.row 6 到 10 放在第 2 节中?

4

1 回答 1

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
  • 可扩展到任意数量的部分

如果您有支持表格单元格的项目的底层数组(或其他平面容器类),这将允许您使用这些项目填写表格视图中的多个部分。

于 2011-10-28T01:19:34.533 回答