2012-02-24 81 views
3

我已经得到了这些单元格,我已经设置了自定义背景颜色。背景色工作正常,当我选择单元格,但是,当我向下滚动,备份,有两种情况:所选的UITableViewCell背景颜色在滚动时发生变化

  1. 如果选择不是很多细胞,就拿出来看的细胞有时会回来在选择时使用默认的蓝色。

  2. 如果大多数或所有的细胞都被选中,那么外出的细胞就会回到预先存在的细胞中的一种颜色 - 即。我选择所有单元格,向下滚动并返回,顶部的单元格与底部单元格(或至少其中一些单元格 - 其他单元格保留其自己的颜色)具有相同的颜色。

这里是我有一个产生这的代码:

- (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重新创建,虽然一些属性得到保存(如标题...)自定义背景不是。

以前有没有人遇到过这种行为?如果是这样,你是如何解决它的?

编辑:即使怪异行为:有时,如果你向后滚动向下和向上,比人选择背景色的“默认”的细胞可以追溯到它的自定义一个。行为似乎是随机的。

+1

你在正确的轨道上:在cellForIndexPath细胞的颜色也应该“renwed”。现在我不在家里的电脑上检查我遇到过类似问题的项目。但是如果我记得正确的话,我必须在willDisplayCell中定义一个单元格的背景颜色:forRowAtIndexPath – 2012-02-24 15:46:17

回答

6

单元格背景色在很多地方都有设置,以确保显示的背景是你想你需要使用一个:

- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath 

详见this问题。如果您需要自定义选择的颜色,那么你应该继承UITableViewCell,并覆盖- (void)setSelected:(BOOL)selected- (void)setHighlighted:(BOOL)highlighted

+0

谢谢 - 这个技巧! – KerrM 2012-02-24 16:08:23

+0

您将要创建一个NSMutableArray来存储所选行的索引路径,这样,您的willDisplayCell就可以知道将所选样式应用于哪些单元格 – yoshyosh 2014-08-26 00:12:01

相关问题