我设置了自定义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
中显示任何类型的 subview 都会有问题。 .任何替代方案或建议将不胜感激。
最佳答案
使用此代码可以更好地完成一些事情。在 setSelected 方法中重新初始化两个 View 是非常低效的。当您使用此代码选择单元格时,您实际上是在清除单元格中的所有内容(我猜这不是您想要的)。最后,您将 selectedBackgroundView 视为当您选择单元格时显示的唯一 View (根据 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;
这将使您的红色方 block 在(且仅当)选择单元格时出现在单元格中的其他 View 之上。来自 Apple 的文档:
UITableViewCell adds the value of this property as a subview only when the cell is selected. It adds the selected background view as a subview directly above the background view (backgroundView) if it is not nil, or behind all other views.
其次,在您的单元格中使用以下代码:
- (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 - selectedBackgroundView 中的自定义 UITableViewCell subview ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12574888/