I am using some static UITableViewCell‘s configured in the Storyboard to display some setting information.
Some of the other cells should be disabled if one of the other settings is toggled off.
In order to put the cells into the proper state, during viewWillAppear I read the settings from NSUserDefaults and then change the cells accordingly.
- (void) viewWillAppear:(BOOL)animated
if ([[NSUserDefaults standardUserDefaults] boolForKey:@"OtherCellEnabled"]) {
[self otherCell].alpha = 1.0;
[self otherCell].userInteractionEnabled = YES;
}
else {
NSLog(@"Changing alpha to 0.3");
[self otherCell].alpha = 0.3;
[self otherCell].userInteractionEnabled = NO;
}
The problem is that when I actually run the program, even though it says in the log that the alpha is changed, the alpha doesn’t actually change. The userInteractionEnabled does seem to stick, but the alpha is left at 1.0.
It’s not a problem of cell reuse, or cell’s not being instantiated in time, because the other settings can be changed just fine.
Changing it from cell.alpha to cell.contentView.alpha works, but that is a different setting.
It seems like all of the settings “stick” except for the alpha setting, which somehow is getting overwritten.
I am answering my own question because I was able to solve it.
First, I tried putting the alpha change in
cellForRowAtIndexPath, but that didn’t work either. After a lot of tinkering, I’ve come to the conclusion thatUITableViewCell‘s alpha setting is somehow special in that it keeps getting overwritten or set to 1.0.I found two fixes:
First, instead of doing the change in
cellForRowAtIndexPath, do it in theUITableViewDelegatemethodwillDisplayCell. For whatever reason, changing the cell’s alpha in this method will actually stick. Of course, if you do it this way you have to re-arrange your logic so that the changes are done on a cell-by-cell basis, i.e.:As I said, I’m not sure exactly why this works in
willDisplayCellbut not incellForRowAtIndexPath. Others seem uncertain also:What is -[UITableViewDelegate willDisplayCell:forRowAtIndexPath:] for?
UITableView background with alpha color causing problem with UITableViewCell
The other solution is to, instead of using the problematic alpha, use another setting which will achieve the same effect. In my case, that was the
contentView.alphaand thebackgroundColor. For whatever reason, these settings will stick, and you can even set them inviewWillAppearand it will work as expected:The disadvantage to the second approach is that now you are overwriting the Storyboard’s cell color settings, but you could work around that by asking the storyboard for the color if you care about that.
I’m not sure why
cell.alphais treated differently. Maybe something about the way static cells are implemented.