我已经创建了一个自定义UITableViewCell。表视图很好地显示了数据。我陷入的是当用户触摸tableview的单元格时,然后我想显示单元格的背景颜色,而不是默认的[蓝色]值,以突出显示单元格的选择。 我使用这段代码,但什么都没有发生:
cell.selectedBackgroundView.backgroundColor=[UIColor blackColor];
我已经创建了一个自定义UITableViewCell。表视图很好地显示了数据。我陷入的是当用户触摸tableview的单元格时,然后我想显示单元格的背景颜色,而不是默认的[蓝色]值,以突出显示单元格的选择。 我使用这段代码,但什么都没有发生:
cell.selectedBackgroundView.backgroundColor=[UIColor blackColor];
当前回答
不需要自定义单元格。如果你只想改变单元格的选定颜色,你可以这样做:
objective - c:
UIView *bgColorView = [[UIView alloc] init];
bgColorView.backgroundColor = [UIColor redColor];
[cell setSelectedBackgroundView:bgColorView];
迅速:
let bgColorView = UIView()
bgColorView.backgroundColor = UIColor.red
cell.selectedBackgroundView = bgColorView
其他回答
我想指出的是,XIB编辑器为您提供了以下标准选项:
部分:蓝色/灰色/没有
(右边有选项的列,第4个标签,第一组“表格视图单元格”,第4个子组,3个项目中的第一个读为“选择”)
也许你想做的事情可以通过选择正确的标准选项来实现。
如果您想向单元格添加自定义高亮显示的颜色(且单元格包含按钮、标签、图像等)。我按照下面的步骤:
例如,如果你想要一个选定的黄色:
1)创建一个适合所有不透明度为20%的单元格(黄色)的视图,例如backgroundselectedView
2)在单元控制器中这样写:
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
self.backgroundselectedView.alpha=1;
[super touchesBegan:touches withEvent:event];
}
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
self.backgroundselectedView.alpha=0;
[super touchesEnded:touches withEvent:event];
}
- (void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event
{
self.backgroundSelectedImage.alpha=0;
[super touchesCancelled:touches withEvent:event];
}
不需要自定义单元格。如果你只想改变单元格的选定颜色,你可以这样做:
objective - c:
UIView *bgColorView = [[UIView alloc] init];
bgColorView.backgroundColor = [UIColor redColor];
[cell setSelectedBackgroundView:bgColorView];
迅速:
let bgColorView = UIView()
bgColorView.backgroundColor = UIColor.red
cell.selectedBackgroundView = bgColorView
覆盖UITableViewCell的setSelected也可以。
override func setSelected(selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Set background color
let view = UIView()
view.backgroundColor = UIColor.redColor()
selectedBackgroundView = view
}
我使用的是ios9.3,通过Storyboard或设置单元格设置颜色。selectionStyle不适合我,但下面的代码工作:
UIView *customColorView = [[UIView alloc] init];
customColorView.backgroundColor = [UIColor colorWithRed:55 / 255.0
green:141 / 255.0
blue:211 / 255.0
alpha:1.0];
cell.selectedBackgroundView = customColorView;
return cell;
我找到了这个解。