我有一些单元格,我设置了自定义背景颜色。当我选择该单元格时,背景颜色可以正常工作。然而,当我向下滚动并再次向上滚动时,可能会发生以下两种情况:
如果未选择许多单元格,则部分移出视图的单元格在选择时有时会恢复为默认的蓝色。
如果选择了大多数或所有单元格,则移出视图的单元格将恢复之前存在的其中一种颜色。例如,我选择所有单元格,向下滚动并重新向上滚动,顶部的单元格具有与底部单元格相同的颜色(至少有一些这样做,其他单元格保持原来的颜色)。
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
UITableViewCell *row = [tableView cellForRowAtIndexPath:indexPath];
UIView *backview = [[UIView alloc] initWithFrame:row.frame];
backview.backgroundColor = [colours objectAtIndex:indexPath.row];
row.selectedBackgroundView = backview;
}
这里是单元格的选定方法更改颜色的地方。单元格是在这里创建的:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = @"eventTypeID";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
NSString *sEventType = [[self.eventTypes valueForKeyPath:@"name.text"] objectAtIndex:indexPath.row];
cell.textLabel.text = sEventType;
return cell;
}
每个单元格的颜色在这里设置:
- (void)loadView {
colours = [[NSMutableArray alloc] init];
CGFloat red[] = {0.84,0.86,0.7,0.46,0.56,0.44,0.95,0.91,0.91,0.76,0.06,0.8,0.73,0.0,0.0,0.01,0.18,0.23,0.57,0.18};
CGFloat green[] = {0.12,0.01,0.07,0.17,0.32,0.18,0.49,0.49,0.78,0.61,0.48,0.85,0.85,0.28,0.38,0.53,0.23,0.36,0.32,0.24};
CGFloat blue[] = {0.34,0.5,0.2,0.53,0.55,0.31,0.18,0.18,0.12,0.27,0.14,0.1,0.49,0.1,0.37,0.49,0.4,0.41,0.55,0.40};
for (int i = 0; i < 20; i++) {
[colours addObject: [UIColor colorWithRed:red[i] green:green[i] blue:blue[i] alpha:1.0]];
}
//Get data from server and parse it
...
}
目前,我刚开始编写 iPhone 程序,但是我的猜测(顺便说一句,这是一个猜测)是单元格会在 cellForRowAtIndexPath
中被重新创建,尽管有些属性(比如标题...)被保存了下来,但自定义背景却没有。
有人遇到过这种情况吗?如果有,您是如何解决的?
编辑:更奇怪的行为:有时,如果您向下滚动并再次向上滚动,曾经变成“默认”选中背景颜色的单元格会重新变回其自定义颜色。这种行为似乎是随机的。