Question

In my app, I have a UITableViewCell which is used to display a background color setting. In the detailTextLabel, it displays the name of the color with the background set to the actual color, e.g. [UIColor cyanColor]. Note that I am setting the background of the detailTextLabel only, not the whole UITableViewCell. When users tap on the cell they are taken to another UITableView which lets them choose a color, and when they return to the previous UITableView the backgroundColor of the UILabel is updated to the new color.

The problem is, whenever I return to the initial UITableView, the UILabel's backgroundColor updates momentarily and then returns to the initial color. I cannot find out why it would be reverting. Any suggestions?

Thank you!

Was it helpful?

Solution

Some state-based properties are set by the table view; I believe that background color is one of them. In other words, the table view is changing the background color of detailTextLabel, probably as part of unhighlighting the selection.

After the table view sets state-based properties, the table delegate is given a final chance to update the appearance of each cell. This is done in the delegate's tableView:willDisplayCell:forRowAtIndexPath: method. Perhaps if you set the background color of detailTextLabel in this method your problem will go away.

OTHER TIPS

When cellForRowAtIndexPath executes, it typically creates and returns a new cell.

From your question, it is unclear if you are recreating the cell or not, but if you are, this could explain the behavior you describe.

Yes..Maybe you are not re-using your cells in cellForRowAtIndexPath methode. If it is, try to re-use your cells rather than creating new one everytime.

The way that I fixed this was to create a UILabel subclass called HighlightedLabel which has the following initialiser:

- (id)initWithHighlightedBackgroundColor:(UIColor *)highlightedBackgroundColor nonHiglightedBackgroundColor:(UIColor *)nonHighlightedBackgroundColor
    {
        self = [super init];
        if(self)
        {
            _highlightedBackgroundColor = highlightedBackgroundColor;
            _nonHighlightedBackgroundColor = nonHighlightedBackgroundColor;
            self.backgroundColor = nonHighlightedBackgroundColor;
        }
        return self;
    }


    -(void)setHighlighted:(BOOL)highlighted
    {
        if(highlighted)
        {
            self.backgroundColor = self.highlightedBackgroundColor;
        }
        else
        {
            self.backgroundColor = self.nonHighlightedBackgroundColor;
        }
    }

Then when I allocate this cell I specify the highlighted and non-highlighted background colour.

This works perfectly - when I select the cell the colour is what I want.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top