selectedBackgroundView

selectedBackgroundView

我已经设置了带有多个标签和一个图像的自定义UITableViewCell,并且(最终)获得了它来查看我想要的外观。

但是,我似乎无法弄清楚如何使选择内容看起来像我想要的样子。我已经实现了setSelected方法,该方法可以让我很好地更改背景颜色,但是我真正想要的是将背景颜色设置为黑色,并在所选单元格的左侧显示彩色矩形(10像素)宽和单元格的高度)。

彩色框将是通过编程设置的颜色,因此尽管我可以轻松地将selectedBackgroundView设置为UIImageView,但这在这种情况下不起作用。

选择单元格时,以下代码将完全不显示selectedViewColor UIView:

- (void)setSelected:(BOOL)selected animated:(BOOL)animated
{
    UIView *selectedView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.selectedBackgroundView.bounds.size.width, self.selectedBackgroundView.bounds.size.height)];
    [selectedView setBackgroundColor:[UIColor blackColor]];

    UIView *selectedView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 10, self.selectedBackgroundView.bounds.size.height)];
    [selectedViewColor setBackgroundColor:[UIColor redColor]];
    [selectedView addSubview:selectedViewColor];

    self.selectedBackgroundView = selectedView;

    [super setSelected:selected animated:animated];
}

这段代码看起来很基础,因此我认为在selectedBackgroundView中显示任何类型的子视图都会出现问题。

任何替代或建议,将不胜感激。

最佳答案

使用此代码可以做一些更好的事情。在setSelected方法中重新初始化两个视图效率很低。使用此代码选择单元格时,实际上实际上是清空了单元格中的所有内容(我猜这不是您想要的)。最后,您将selectedBackgroundView视为选择单元格时唯一显示的视图(根据Apple的文档,它显示在backgroundView上)。

尝试使用以下(已编辑)-
将此代码放在创建单元的位置(大概是cellForRowAtIndexPath :)

UIView* container = [[UIView alloc] initWithFrame:CGRectMake(0, 0, cell.backgroundView.bounds.size.width, cell.backgroundView.bounds.size.height)]; // we need this because in cells, the background views always take up the maximum width, regardless of their frames.
container.backgroundColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:0]; // make it transparent - we only want the square subview to be seen.
UIView *selectedViewColor = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 10, self.selectedBackgroundView.bounds.size.height)];
[selectedViewColor setBackgroundColor:[UIColor redColor]];
[container addSubview:selectedViewColor]
cell.selectedBackgroundView = container;

当(仅当)选中该单元格时,这将使您的红色正方形出现在该单元格的其他视图上方。从苹果的文档:

仅当选择单元格时,UITableViewCell才会将此属性的值添加为子视图。它将选定的背景视图添加为子视图,如果它不是nil,则直接在背景视图(backgroundView)上方,或在所有其他视图的后面。

其次,在单元格中使用以下代码:
- (void)setSelected:(BOOL)selected animated:(BOOL)animated
{
   [super setSelected:selected animated:animated];
   if(selected == YES)
   {
      self.backgroundView.backgroundColor = [UIColor blackColor];
   }
   else
   {
      self.backgroundView.backgroundColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:0] // replace this with whatever's appropriate - a return to the unselected state.
   }
}

这样可以确保选中单元格时,背景变为黑色(不会干扰显示的内容。希望这些更改也可以解决您遇到的问题。

关于ios - iOS-selectedBackgroundView中的自定义UITableViewCell subview ,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/12574888/

10-12 02:05