Search code examples
objective-caccessoryviewuitableview

UITableViewCell: Accessory View going away when selected


I might be going about this all wrong, so hopefully someone will tell me what I should be doing.

I have constructed a table view to act as a legend and color picker. In the AccessoryView slot, I places a custom view that is just a colored box. User will show the legend, so they know what colors mean what, and they can pick on a color to then 'colorize' a drawing by assigning that color to objects. All of that works just fine.

What I'm having a problem with is the selected row style. When I select a row from the legend, the cell goes blue, like it should, but my AccessoryView has now disappeared. I don't want this to happen. However, I don't know what to set to make it not disappear. Keep in mind, I still want a row to show up as 'selected'. But any way that I do that, my accessory view disappears (most likely is hidden by the selected color).

Here's how I'm setting the accessory view right now.

CGRect colorBox = CGRectMake(0, 0, 30, 30);
UIView *colorView = [[UIView alloc] initWithFrame:colorBox];
colorView.backgroundColor = [self colorWithHexString:[selOption valueForKey:@"qoColor"]];
cell.accessoryView = colorView;

Solution

  • You can use a UIImageView instead of a UIView, which won't disappear when the cell is selected. You can either make tiny .png thumbnails for each color (if there aren't a lot) or you can create them dynamically in your cellForRowAtIndexPath delegate method, ala:

    UIImageView *colorView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 30, 30)];
    
    CGRect rect = CGRectMake(0.0f, 0.0f, 30.0f, 30.0f);
    UIGraphicsBeginImageContext(rect.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    
    CGContextSetFillColorWithColor(context, [[self colorWithHexString:[selOption valueForKey:@"qoColor"]]; CGColor]);
    CGContextFillRect(context, rect);
    
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    [colorView setImage:image];
    
    [cell setAccessoryView:colorView];
    [colorView release];