Ios 是否可以为每个部分设置单元格背景色?
我试图根据分区号设置单元格背景颜色,但效果不太好。当我来回滚动时,单元格颜色会改变,并且是错误的。我正在尝试使用一个颜色变量来实现它,该变量在Ios 是否可以为每个部分设置单元格背景色?,ios,objective-c,Ios,Objective C,我试图根据分区号设置单元格背景颜色,但效果不太好。当我来回滚动时,单元格颜色会改变,并且是错误的。我正在尝试使用一个颜色变量来实现它,该变量在willDisplayHeaderView中设置,然后在willDisplayCell中使用。代码如下: - (void)tableView:(UITableView *)tableView willDisplayHeaderView:(UIView *)view forSection:(NSInteger)section{ if(sec
willDisplayHeaderView
中设置,然后在willDisplayCell
中使用。代码如下:
- (void)tableView:(UITableView *)tableView willDisplayHeaderView:(UIView *)view forSection:(NSInteger)section{
if(section % 2 == 0){
self.currentCellColor =[UIColor colorWithRed:(199/255.0) green:(214/255.0) blue:(156/255.0) alpha:1];
}
else{
self.currentCellColor = [UIColor colorWithRed:(242/255.0) green:(245/255.0) blue:(232/255.0) alpha:1];
}
}
- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
cell.backgroundColor = self.currentCellColor;
}
此外,各部分对这项功能也不重要,因此,如果有人在一个大部分中有更好/更容易实现这一点的方法,请随时提出建议。我只需要每4行更改一次颜色。如果是我,我会为每个部分设置一个不同的单元格标识符,然后在
cellForRowAtIndexPath:
中设置该单元格的颜色,这样在滚动和tableView重用您的单元格时,您可以确保它不会获取错误颜色的单元格 试试这个
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"identifier"];
....
if (indexPath.section % 2) {
cell.contentView.backgroundColor = [UIColor redColor];
}
else {
cell.contentView.backgroundColor = [UIColor blueColor];
}
return cell;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *cellIdentifier = @"cellIdentifier";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
....
if(indexPath.section % 2 == 0){
self.currentCellColor =[UIColor colorWithRed:(199/255.0) green:(214/255.0) blue:(156/255.0) alpha:1];
}
else{
self.currentCellColor = [UIColor colorWithRed:(242/255.0) green:(245/255.0) blue:(232/255.0) alpha:1];
}
cell.contentView.backgroundColor = self.currentCellColor;
....
return cell;
}
您是否在
cellForRowAtIndexPath:
中尝试了此操作?而不是在willDisplayCell:
中尝试了此操作。?还是与之结合?还是别的什么?我也试着在那里设置它,但在滚动时仍然会出错。除了willDisplayCell
和willDisplayHeaderView
之外,我没有意识到我可以从indexPath获得该部分,谢谢!