2

我在 cellForRowAtIndexPath 方法中为 UITableViewCell 正确设置 selectedBackgroundView 时遇到了一些困难。我尝试了一些代码变体......

CGRect customFrame = CGRectMake(cell.frame.origin.x + 1.0f, cell.frame.origin.y,
cell.frame.size.width - 22.0f, cell.frame.size.height);

UIView *cellBackground = [[[UIView alloc] initWithFrame:customFrame] autorelease];
cellBackground.backgroundColor = [UIColor colorWith8BitRed:0 green:0 blue:0 alpha:0.1f];
cell.selectedBackgroundView = cellBackground;

使用此代码段,单元格显示出正确的颜色变化,但框架尺寸不是我指定的(它们似乎是 cell.frame 的尺寸,即使我指定了要使用我的 customFrame 初始化的视图)

我尝试了另一种方法:创建带有子子视图的父视图。父视图的框架与单元格的尺寸相同,子视图的框架包含我的 customFrame 尺寸。当我将父视图设置为背景视图时,将应用我的框架 customFrame 尺寸。但是,当我尝试将父视图设置为 selectedBackgroundView 时,选择单元格时看不到任何视图。

CGRect customFrame = CGRectMake(cell.frame.origin.x + 1.0f, cell.frame.origin.y, 
cell.frame.size.width - 22.0f, cell.frame.size.height);

UIView *parentView = [[[UIView alloc] initWithFrame:cell.frame] autorelease]; 
UIView *childView = [[[UIView alloc] initWithFrame: customFrame] autorelease];

[parentView addSubview:childView];
childView.backgroundColor = [UIColor colorWith8BitRed:0 green:0 blue:0 alpha:0.1f];
cell.selectedBackgroundView = parentView;

自定义 selectedBackgroundView 的框架尺寸似乎相当困难。任何帮助,将不胜感激。谢谢!

4

1 回答 1

12

您在自定义 TableViewCell 中需要这个

- (void)layoutSubviews
{
    [super layoutSubviews];
    self.selectedBackgroundView.frame = CGRectMake(cell.frame.origin.x + 1.0f, cell.frame.origin.y, cell.frame.size.width - 22.0f, cell.frame.size.height);
}

我不得不挠头。这有点愚蠢,因为一种或另一种方式你需要两倍的帧。当然,您可以使用define甚至是UIView自身的属性,但仍然......

多亏了Ortwin Gentz,我才能找到这一点——对他的支持!

于 2013-04-26T21:07:39.457 回答