Swift: Can't set the background of custom UITableViewCell to .clear

I have created the following UITableViewCell

class SeasonTableViewCell: UITableViewCell {

static let identifier = "SeasonTableViewCell"

private var seasonLabel: UILabel = {
    let label = UILabel()
    label.numberOfLines = 1
    label.textAlignment = .center
    return label

override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
    super.init(style: style, reuseIdentifier: reuseIdentifier)
    contentView.backgroundColor = .clear
    [seasonLabel].forEach { contentView.addSubview($0) }



However, the cells render with the default background. If however I try to use any other color:

contentView.backgroundColor = .red

This does work. It’s just with .clear that it doesn’t work.

I have also tried the following when dequeueing the cell:

cell.backgroundView?.backgroundColor = .clear

But this doesn’t work either.

How can I make the cell have a transparent background?

>Solution :

As the comment says self.backgroundColor = UIColor.clear is enough in init at TableviewCell to give background color to cell.

If your main color is in Viewcontroller's view make

tableview.backgroundColor = .clear // in view
self.backgroundColor = UIColor.clear // in cell init class

If your main color is in tableview’s background, just make

 self.backgroundColor = UIColor.clear // in cell init class

I don’t see inside the setConstraints method but I think the label covers the whole cell and if the label has a background color this may result in not getting the result you want.Don’t ignore it either

Leave a Reply