Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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) }
    setConstraints()
}

...

}

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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
and
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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading