滚动时选择UITableViewCell背景颜色更改

时间:2012-02-24 15:33:52

标签: iphone objective-c uitableview scroll

我已经为这些单元格设置了自定义背景颜色。当我选择单元格时,背景颜色很好,但是,当我向下滚动并向后滚动时,会发生两件事情:

  1. 如果选择的单元格不是很多,则选中时,视图中的单元格有时会返回默认的蓝色。

  2. 如果选择了大部分或全部细胞,那么熄灭的细胞将返回其中预先存在的细胞中的一种颜色 - 即。我选择所有单元格,向下滚动并向上移动,顶部的单元格与底部单元格的颜色相同(或至少部分单元格 - 其他单元格保留自己的颜色)。

  3. 以下是我生成的代码:

    - (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,但我的猜测(这是一个疯狂的btw)是在cellForRowAtIndexPath中重新创建单元格,虽然一些属性得到了保存(像标题...)自定义背景不是。

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

    编辑:甚至更奇怪的行为:有时,如果你向下和向上滚动,那么已经转到“默认”选定背景颜色的单元格会回到它的自定义颜色。这种行为似乎是随机的。

1 个答案:

答案 0 :(得分:7)

在许多地方设置了单元格背景颜色,以确保显示的背景是您需要使用的背景:

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

有关详细信息,请参阅this问题。如果您需要自定义选择颜色,那么您应该继承UITableViewCell并覆盖- (void)setSelected:(BOOL)selected- (void)setHighlighted:(BOOL)highlighted

相关问题