我已经创建了一个自定义UITableViewCell。表视图很好地显示了数据。我陷入的是当用户触摸tableview的单元格时,然后我想显示单元格的背景颜色,而不是默认的[蓝色]值,以突出显示单元格的选择。 我使用这段代码,但什么都没有发生:
cell.selectedBackgroundView.backgroundColor=[UIColor blackColor];
我已经创建了一个自定义UITableViewCell。表视图很好地显示了数据。我陷入的是当用户触摸tableview的单元格时,然后我想显示单元格的背景颜色,而不是默认的[蓝色]值,以突出显示单元格的选择。 我使用这段代码,但什么都没有发生:
cell.selectedBackgroundView.backgroundColor=[UIColor blackColor];
当前回答
我使用的是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;
我找到了这个解。
其他回答
如果你有一个分组表,每个部分只有一个单元格,只需在代码中添加额外的一行: bgColorView.layer.cornerRadius = 10;
UIView *bgColorView = [[UIView alloc] init];
[bgColorView setBackgroundColor:[UIColor redColor]];
bgColorView.layer.cornerRadius = 10;
[cell setSelectedBackgroundView:bgColorView];
[bgColorView release];
不要忘记导入QuartzCore。
使用[cell setClipsToBounds:YES];对于分组样式单元格
我使用下面的方法,对我来说很好,
class MyTableViewCell : UITableViewCell {
var defaultStateColor:UIColor?
var hitStateColor:UIColor?
override func awakeFromNib(){
super.awakeFromNib()
self.selectionStyle = .None
}
// if you are overriding init you should set selectionStyle = .None
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
if let hitColor = hitStateColor {
self.contentView.backgroundColor = hitColor
}
}
override func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?) {
if let defaultColor = defaultStateColor {
self.contentView.backgroundColor = defaultColor
}
}
override func touchesCancelled(touches: Set<UITouch>?, withEvent event: UIEvent?) {
if let defaultColor = defaultStateColor {
self.contentView.backgroundColor = defaultColor
}
}
}
[cell setSelectionStyle:UITableViewCellSelectionStyleGray];
确保你已经使用了上面的行来使用选择效果
我认为你在正确的轨道上,但根据selectedBackgroundView的类定义:
对于普通样式表(UITableViewStylePlain)中的单元格,默认为nil,对于section-group表(UITableViewStyleGrouped)中的单元格,默认为非nil。
因此,如果你使用的是普通样式的表,那么你需要alloc-init一个新的UIView,有你想要的背景颜色,然后分配给selectedBackgroundView。
或者,如果你想要的是灰色背景当单元格被选中时,你可以使用这个:
cell.selectionStyle = UITableViewCellSelectionStyleGray;