changing text color in custom UITableViewCell iphone

11,901

Solution 1

In your didSelectRowAtIndexPath method, make a call to get the current cell and update accordingly:

CheckListCell* theCell = (CheckListCell*)[tableView cellForRowAtIndexPath:indexPath];
theCell.nameLabel.textColor = [UIColor lightGrayColor];
theCell.colorLabel.textColor = [UIColor lightGrayColor];

Solution 2

Since you are using a custom table cell, you can implement code to set the label colors by implementing the setSelected and setHighlighted methods in your custom UITableViewCell. This will capture all state changes from selection, although there are some tricky cases, like when setHighlighting is called with NO when you select and drag outside the cell after it was already selected. Here is the approach I used, which I believe sets the color appropriately in all cases.

- (void)updateCellDisplay {
    if (self.selected || self.highlighted) {
        self.nameLabel.textColor = [UIColor lightGrayColor];
        self.colorLabel.textColor = [UIColor lightGrayColor];
    }
    else {
        self.nameLabel.textColor = [UIColor blackColor];
        self.colorLabel.textColor = [UIColor blackColor];
    }
}

- (void)setHighlighted:(BOOL)highlighted animated:(BOOL)animated {
    [super setHighlighted:highlighted animated:animated];
    [self updateCellDisplay];
}

- (void) setSelected:(BOOL)selected animated:(BOOL)animated {
    [super setSelected:selected animated:animated];
    [self updateCellDisplay];
}
Share:
11,901
Brodie
Author by

Brodie

Updated on June 27, 2022

Comments

  • Brodie
    Brodie almost 2 years

    I have a custom cell and when the user selects that cell, I would like the text in the two UILabels to change to light gray.

    ChecklistCell.h:

    #import <UIKit/UIKit.h>
    
    
    @interface ChecklistCell : UITableViewCell {
        UILabel *nameLabel;
        UILabel *colorLabel;
        BOOL selected;
    
    
    }
    
    @property (nonatomic, retain) IBOutlet UILabel *nameLabel;
    @property (nonatomic, retain) IBOutlet UILabel *colorLabel;
    
    
    
    @end
    

    ChecklistCell.m:

    #import "ChecklistCell.h"
    
    
    @implementation ChecklistCell
    @synthesize colorLabel,nameLabel;
    - (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier {
        if ((self = [super initWithStyle:style reuseIdentifier:reuseIdentifier])) {
            // Initialization code
        }
        return self;
    }
    
    
    - (void)setSelected:(BOOL)selected animated:(BOOL)animated {
    
        [super setSelected:selected animated:animated];
    
        // Configure the view for the selected state
    }
    
    
    - (void)dealloc {
        [nameLabel release];
        [colorLabel release];
            [super dealloc];
    }
    
    
    @end