在自定义UITableViewCell iphone中更改文本颜色

Bro*_*die 4 iphone uitableview ipad

我有一个自定义单元格,当用户选择该单元格时,我希望两个UILabel中的文本更改为浅灰色.

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
Run Code Online (Sandbox Code Playgroud)

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
Run Code Online (Sandbox Code Playgroud)

Mat*_*t R 13

由于您使用的是自定义表格单元格,因此可以通过在自定义UITableViewCell中实现setSelected和setHighlighted方法来实现代码来设置标签颜色.这将从选择中捕获所有状态更改,尽管存在一些棘手的情况,例如当您选择并在单元格已经被选中后拖动到单元外时,使用NO调用setHighlighting时.这是我使用的方法,我相信在所有情况下都适当地设置颜色.

- (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];
}
Run Code Online (Sandbox Code Playgroud)


Ben*_*ams 5

在您的didSelectRowAtIndexPath方法中,进行调用以获取当前单元格并相应地更新:

CheckListCell* theCell = (CheckListCell*)[tableView cellForRowAtIndexPath:indexPath];
theCell.nameLabel.textColor = [UIColor lightGrayColor];
theCell.colorLabel.textColor = [UIColor lightGrayColor];
Run Code Online (Sandbox Code Playgroud)