Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift 4 backgroundColor bug?

I have a problem with transparency in my Views, especially with UITableView.

Just to make sure. I already have 3 years of experience with swift and this is the first time, I am getting this problem.

So in apple's docs it says the following: backgroundColor The view's background color.

Changes to this property can be animated. The default value is nil, which results in a transparent background color."

But when applying clear color to backgroundColor or tableView.backgroundColor = UIColor.clear, the background is still appearing white.

Is this a bug or a feature?

EDIT:

The tableView isn't the problem anymore. It is the cell within the tableView. Already tried solutions are clearing the background color of all subviews. Nothing changed.

EDIT 29.09.17

Ok, I debugged my application and got this:

UICachedDeviceWhiteColor and cachedColor.

UICachedDeviceWhiteColor

A google searching also didn't help.

Edit 29.09.2017 Later that day ...

The problem occurs, when updating from swift 3 to swift 4. I made a new project with swift 4, but it actually works fine. Because it is a problem I have to solve. I will try some things and update this post from time to time.

like image 821
user2982195 Avatar asked Sep 10 '25 23:09

user2982195


1 Answers

In UITableViewCell and UICollectionViewCell there is a property view called contentView.

A common mistake is to manipulate the cell directly. Instead try to manipulate the cells content view:

Obj-c

UITableViewCell *cell = ....// get the cell

cell.backgroundColor = ... // BAD !

cell.contentView.backgroundColor = [UIColor redColor] // this is the correct way.

Swift

let cell = ...
cell.contentView.backgroundColor = UIColor.red // make sure its the contentView 

also a couple small nuances with colors and opacity:

If you want only the background to have opacity (i.e. less than 100%) , make sure you are not changing the view's opacity (i.e. view.alpha = 0.5 BAD) - change the color's opacity value instead:

i.e.

cell.contentView.backgroundColor = [UIColor colorWithRed:... green:... blue:... alpha:0.5];

Another useful trick is to pause the application and press the "visual debug" button.

Search for your view and check it's attributes in the inspector

like image 140
Avner Barr Avatar answered Sep 13 '25 14:09

Avner Barr