自定义UITableViewCell中的selectedBackgroundView

时间:2011-07-26 21:34:00

标签: cocoa-touch ios4 uitableview

所以我有一个直接从nib文件加载的单元格:

NSArray *cellContents = [[NSBundle mainBundle] loadNibNamed:@"ResultsTableViewCell" owner:self options:nil];
        cell = [cellContents objectAtIndex:0];

在nib文件中,有一个UITableViewCell和两个UIViews,每个都有自己的子视图。结构:

-TableViewCell
   Label 1
   Label 2
-UIView A
   UIView a
   UIView b
   UIImageView c
   UIImageView d
-UIView B
   UIView e
   UIView f
   UIImageView g
   UIImageView h

因此UIView A连接到UITableViewCell的backgroundView属性,UIView B连接到selectedBackgroundView属性。

问题: 那么为什么A显示为具有所有子视图的单元格的背景,并且B中的UIImageViews工作正常,但B中的UIViews根本没有显示但是我改变了它?谢谢!

1 个答案:

答案 0 :(得分:0)

这是我发现我的情况。当我记录UIView的背景颜色的RGB和alpha时,我发现当选择单元格时它们都被设置为0:

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    CGFloat red, green, blue, alpha;
    [viewE.backgroundColor getRed:&red green:&green blue:&blue alpha:&alpha];
    NSLog(@"Selected: Red=%f, Green=%f, Blue=%f, alpha=%f", red, green, blue, alpha);
}

-(void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(NSIndexPath *)indexPath {
    CGFloat red, green, blue, alpha;
    [viewE.backgroundColor getRed:&red green:&green blue:&blue alpha:&alpha];
    NSLog(@"Deslected: Red=%f, Green=%f, Blue=%f, alpha=%f", red, green, blue, alpha);
}

最初,没有选择任何内容。点击表格中的一行,日志显示:

Selected: Red=0.000000, Blue=0.000000, Green=0.000000, alpha=0.000000

并且我的子视图没有出现(注意Alpha = 0)。有趣,因为当我记录viewE.alpha时,它显示它是1。

再次点击该行以取消选择:

Deselected: Red=0.667000, Blue=0.776000, Green=0.220000, alpha=1.000000

这就是我的期望。

我的表格单元格是自定义的UITableViewCell。所以在我的自定义UITableViewCell类中,我添加了以下代码:

- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
    UIColor *saveColor = self.viewE.backgroundColor;
    [super setSelected:selected animated:animated];
    if (selected)
        self.viewE.backgroundColor = saveColor;
}

现在,选择单元格时会出现子视图。

看起来这里的代码补偿了一个本来不应该存在的条件,但是它有效!