按 UITableViewCell 时 Circle View 消失了

Circle View is gone when press UITableViewCell

在 UITableViewCell 的 contentView 中,我放了一个 UIView 并将其图层 cornerRadius 设置为其高度的一半,使其 circle.And 将其颜色设置为红色。 当我运行它并按下UITableViewCell时,红色圆圈变透明。

在按下单元格之前。

按下单元格后。

哪里出错了,我觉得是跟cornerRadius有关。谁能帮帮我?

因为 UITableviewCell 在选中时会更改视图背景颜色。

您需要子类化 UITableviewCell,并将背景色改回

截图

代码

class CustomCell:UITableViewCell{
override func setHighlighted(highlighted: Bool, animated: Bool) {
    super.setHighlighted(highlighted, animated: animated)
    let view = self.viewWithTag(10) //The tag of this view is 10
    view?.backgroundColor = UIColor.redColor()
}
override func setSelected(selected: Bool, animated: Bool) {
    super.setSelected(selected, animated: animated)
    let view = self.viewWithTag(10)
    view?.backgroundColor = UIColor.redColor()
}
} 

正如我已经回答的 :

UITableViewCell changes the background color of all sub views when cell is selected or highlighted.

我已针对您的问题修改了之前的回答

您有三个选择:

  1. 如果你不想要任何选择样式

    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
  2. 子类 UITableViewCell 并覆盖 Tableview 单元格的 setSelected:animated and/or setHighlighted:animated 喜欢 回答

  3. 将圆添加为图层

    CALayer* layer = [CALayer layer];
    layer.frame = CGRectMake(10, 10, 30, 30);
    layer.backgroundColor = [UIColor redColor].CGColor;
    layer.cornerRadius = 20/2.0f;
    [cell.contentView.layer  addSublayer:layer];