0

我是 iPhone 开发的新手。我有一个包含多个部分的表格视图。我正在改变这样的单元格的颜色,它工作正常。

if ([indexpath row]%2)
{
    trackCell.contentView.backgroundColor = [UIColor clearColor];
}
else
{
    trackCell.contentView.backgroundColor = [UIColor colorWithRed:212/255.0 green:212/255.0 blue:212/255.0 alpha:0.1];
}

但是现在一个部分的最后一个单元格与下一个部分的第一个单元格具有相同的颜色。我该如何解决这个问题?

4

4 回答 4

2

这很脏,但是您可以计算当前单元格之前的所有单元格,然后使用该计数来计算所需的颜色。这是未经测试的,但应该这样做:

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

   cellCount+=indexPath.row;

   if(cellCount%2==0)
   {
    //set one color
   }
   else
   {
    //set other color 
   }
   // blah
}
于 2013-02-01T13:31:12.300 回答
1

问题是,如果单元格在第 1 节(或 2、3、...)中,并且前一节有奇数个单元格,则它以与前一个单元格的最后一个单元格相同的颜色结束。

因此,您需要检查上一节的单元格数,如果该数字是奇数,请反转您的“if”语句,如果它是偶数则保持原样

编辑:

int toBeAdded = 0;
if (indexPath.section>0) {
    toBeAdded = ([self tableView:tableView numberOfRowsInSection:(indexPath.section -1)]) %2 ;
}

if (([indexpath row]+toBeAdded)%2) {
    trackCell.contentView.backgroundColor = [UIColor clearColor];
} else {
    trackCell.contentView.backgroundColor = [UIColor colorWithRed:212/255.0 green:212/255.0 blue:212/255.0 alpha:0.1];
}

编辑2:

看到“Will Jenkins”...他是对的...您需要查看所有前面的部分,而不仅仅是前一个...

他计算一个部分中所有单元格的方法不如我的好和快,但他的答案是正确的,+1 对他来说......无论如何,最好的方法可能是将他的循环和我对 tableView 的调用结合起来: tableView numberOfRowsInSection:

于 2013-02-01T13:08:02.267 回答
0

这是由于您在每个部分中的行数...

假设您尝试为奇数行提供红色,为偶数行提供绿色,并且第一节有3 行,那么最后一个单元格将具有红色,第二节的第一个单元格也具有红色。

因此,您只需要检查Previous Section 中的行数。如果是偶数,则应保持颜色顺序,否则只需更改该部分的颜色顺序。

于 2013-02-01T13:10:37.893 回答
0

关于部分更改颜色,需要编写自己的逻辑,例如,

需要使用静态 int 值而不考虑部分,并使用已经使用的代码并将 indexpath.row 替换为您的值。IE

静态 int 索引;

  if ( Index % 2)
   {
     trackCell.contentView.backgroundColor = [UIColor clearColor];
   } else  {
trackCell.contentView.backgroundColor = [UIColor colorWithRed:212/255.0 green:212/255.0 blue:212/255.0 alpha:0.1];
   }
 Index++;
于 2013-02-01T13:09:26.727 回答