Problem making UITableViewCell text white when selected - iphone

When my user clicks on a cell I want the text to turn white:
- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
[super setSelected:selected animated:animated];
lblName.textColor = [UIColor whiteColor];
lblTime.textColor = [UIColor whiteColor];
}
This works fine, but when the user selects another cell, the previous cell's text color remains white. How can I revert it back to black?

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
static NSIndexPath *oldIndexPath;
UITableViewCell *cell1 = [tableView cellForRowAtIndexPath:indexPath];
UITableViewCell *cell2 = [tableView cellForRowAtIndexPath:oldIndexPath];
cell1.textLabel.textColor = [UIColor whiteColor];
cell2.textLabel.textColor = [UIColor blackColor];
oldIndexPath = indexPath;
}

Related

How to change the backgroundColor for all UITableViewCells

I have a very simple view controller which has only a UITableView and a UIButton, when tapping the button, I want to change the color of the background of all UITableViewCells to green, giving that there are some cells not visible, I use this loop to accomplish what I need:
- (IBAction)click:(id)sender {
for (int row = 0; row < [self.tableView numberOfRowsInSection:0]; row++) {
NSIndexPath* cellPath = [NSIndexPath indexPathForRow:row inSection:0];
UITableViewCell* cell = [self.tableView cellForRowAtIndexPath:cellPath];
cell.backgroundColor = [UIColor greenColor];
}
}
the problem is with the default behavior of the UITableView, it does not actually create the invisible cells until they are visible !! so the above code unfortunately works ONLY on visible cells. The question is, how can I change the color of all cells on button tap ?
p.s. this very simple project sample can be downloaded here.
thank you in advance.
you don't have to do like this
just use a variable to save the backgroundColor of cells
UIColor cellColor;
then when you change the color call
[tableView reloadData];
then in
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = yourcell;
...
...
...
cell.backgroundColor = cellColor;
return cell ;
}
it's done!
update
sorry , try this
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = yourcell;
...
...
...
cell.textLabel.backgroundColor = [UIColor clearColor];
UIView* bgview = [[UIView alloc] initWithFrame:cell.bounds];
bgview.backgroundColor = [UIColor greenColor];
[cell setBackgroundView:bgview];
return cell ;
}
You want to use the UITableViewDataSource to handle this, so just create a UIColor variable in your .h file, change the variable in your action and tell the tableView to reload it's data, and then set the color in the data source response.
MyTableViewController.h
#interface MyTableViewController : UITableViewController {
UIColor *cellColor;
}
-(IBAction)click:(id)sender;
MyTableViewController.m
#implementation MyTableViewController
-(IBAction)click:(id)sender{
cellColor = [UIColor redColor];
[self.tableView reloadData];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
// Setup your cell
cell.textLabel.backgroundColor = [UIColor clearColor];
cell.detailTextLabel.backgroundColor = [UIColor clearColor];
cell.accessoryView.backgroundColor = [UIColor clearColor];
cell.contentView.backgroundColor = cellColor;
return cell;
}
#end
You state in a comment to Paul Hunter's answer "does not color the whole cells".
Try setting a backgroundView:
cell.backgroundView = [[[UIView alloc] init] autorelease];
cell.backgroundView.backgroundColor = self.cellColor;
Store the color as a retained property and set it when you click the button.
#property (retain, nonatomic) UIColor *cellColor;
....
- (IBAction)click:(id)sender {
self.cellColor = [UIColor greenColor];
for (int row = 0; row < [self.tableView numberOfRowsInSection:0]; row++) {
NSIndexPath* cellPath = [NSIndexPath indexPathForRow:row inSection:0];
UITableViewCell* cell = [self.tableView cellForRowAtIndexPath:cellPath];
cell.contentView.backgroundColor = self.cellColor;
cell.textLabel.backgroundColor = self.cellColor;
}
}
You could also choose to reload the whole tableView instead of iterating through the cells.
- (IBAction)click:(id)sender {
self.cellColor = [UIColor greenColor];
[self.tableView reloadData];
}
Then in your tableView:cellForRowAtIndexPath: check if the property is set and set the contentView and textLabel background colors.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
...
if (self.cellColor) {
cell.contentView.backgroundColor = self.cellColor;
cell.textLabel.backgroundColor = self.cellColor;
}
return cell;
}
In your code just change this method
may be this is your temporary solution
-(IBAction)click:(id)sender
{
self.tableView.backgroundColor=[UIColor greenColor];
}
this link can solve your problem ,it have similar problem like your
Setting background color of a table view cell on iPhone

can't change UITableViewCell background color

I have UITableViewCell that fits on UITableView, but somehow I can't change the background color when entering editing style mode.. I've tried everything on the web, search all day long, but still couldn't get it fixed (I've searched StackOverflow as-well). please, help me.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
MainTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
NSArray* views = [[NSBundle mainBundle] loadNibNamed:#"MainTableViewCell" owner:nil options:nil];
for (UIView *view in views) {
if([view isKindOfClass:[UITableViewCell class]])
{
cell = (MainTableViewCell *)view;
}
}
}
Try customizing the cell inside tableView: willDisplayCell: method, something like this:
- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
cell.backgroundColor = [UIColor redColor];
}
You need to change the tableView cell's contentView, not the cell's background view.
- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
cell.contentView.backgroundColor = [UIColor redColor];
}
to have total control on the customisation of your cells, I prefer better to override the cell view,
create a new class for your cell view, that gets called by the UITableView,
later when i get to my work computer if you havent found your answer I will post some sample code,
once you see how it works is pretty easy
you could as well place an image for your cell background, and place different labels and images, buttons, textfields in custom places of your cell,
EDIT>>
the code! [is overkill just to change the background, but if you want to really customise your cell, this is the way to go!]
in your CustomCell.h
#import <UIKit/UIKit.h>
#interface CustomCell : UITableViewCell {
UILabel *_kLabel;
UILabel *_dLabel;
}
#property (nonatomic, retain) UILabel *kLabel;
#property (nonatomic, retain) UILabel *dLabel;
- (void) initLabels;
#end
in your CustomCell.m
#import "CustomCell.h"
#implementation CustomCell
#synthesize kLabel = _kLabel;
#synthesize dLabel = _dLabel;
- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
if (self) {
// Initialization code
CGRect popUpImageBgndRect = CGRectMake(0, 0, 942, 44);
UIImageView *popUpImageBgnd = [[UIImageView alloc] initWithFrame:popUpImageBgndRect];
[popUpImageBgnd setImage:[UIImage imageNamed:#"tableCellBgnd.png"]];
popUpImageBgnd.opaque = YES; // explicitly opaque for performance
[self.contentView addSubview:popUpImageBgnd];
[popUpImageBgnd release];
[self initLabels];
}
return self;
}
- (void)layoutSubviews {
[super layoutSubviews];
CGRect contentRect = self.contentView.bounds;
CGFloat boundsX = contentRect.origin.x;
CGRect frame;
frame= CGRectMake(boundsX+10 ,10, 200, 20);
self.kLabel.frame = frame;
frame= CGRectMake(boundsX+98 ,10, 100, 20);
self.dLabel.frame = frame;
- (void)setSelected:(BOOL)selected animated:(BOOL)animated
{
[super setSelected:selected animated:animated];
// Configure the view for the selected state
}
- (void) initLabels {
self.kLabel = [[[UILabel alloc]init] autorelease];
self.kLabel.textAlignment = UITextAlignmentLeft;
self.kLabel.backgroundColor = [UIColor clearColor];
self.kLabel.font = [UIFont fontWithName:#"FS Albert" size:16];
self.kLabel.textColor = [UIColor colorWithRed:51.0f/255.0f green:51.0f/255.0f blue:51.0f/255.0f alpha:1];
self.dLabel = [[[UILabel alloc]init] autorelease];
self.dLabel.textAlignment = UITextAlignmentLeft;
self.dLabel.backgroundColor = [UIColor clearColor];
self.dLabel.font = [UIFont systemFontOfSize:16];
self.dLabel.textColor = [UIColor colorWithRed:51.0f/255.0f green:51.0f/255.0f blue:51.0f/255.0f alpha:1];
[self.contentView addSubview:self.kLabel];
[self.contentView addSubview:self.dLabel];
}
-(void) dealloc {
[_kLabel release];
[_dLabel release];
[super dealloc];
}
#end
And in your ViewController.m
YourViewController.m
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"Cell";
CustomCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[CustomCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
}
return cell;
}
ENJOY!!
;)
try setting the cells backgroundColor property, worked for me cell.backgroundColor=[UIColor blueColor];
Please try this, it works for me.
UIView *bgView = [[UIView alloc] initWithFrame:cell.frame];
bgView.backgroundColor = [UIColor greenColor];
cell.backgroundView = bgView;
[bgView release];
As #Westley mentioned;
You need to change the tableView cell's contentView, not the cell's background view.
This is how you should do it:
if(index == conditionYouWant)
{
cell.contentView.backgroundColor = [UIColor whiteColor];
}
else
{
cell.contentView.backgroundColor = [UIColor colorWithRed:0.925 green:0.933 blue:0.937 alpha:1.0];
}
Hope it helps you guys out
Be sure you didn't already set the content view's background color in the Storyboard. If you did, changing the cell.backgroundColor in code will make no difference, and you will go round and round in confusion (like I did).
cell.backgroundColor = [UIColor redColor];
in swift 3 you can use
cell.backgroundcolor = UIColor.white

How to change tableViewCell background color

NOTE: this is about a cell in GROUPED tableView. That makes a HUGE difference, when compared to normal tableView! The default cell customization answers do NOT work in this case, so please verify your answer first.
This is how I set gray screen and yellow tableView background:
- (void)viewDidLoad
{
[super viewDidLoad];
self.view.backgroundColor = [UIColor grayColor];
UIView *myView = [[UIView alloc] initWithFrame:magicRect];
myView.backgroundColor = [UIColor yellowColor];
[self.tableView addSubview:myView];
[self.tableView sendSubviewToBack:myView];
}
This is how I set green cell background. As you can see from picture, it's missing some areas:
- (UITableViewCell *)tableView:(UITableView *)tableView
cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell =
[tableView dequeueReusableCellWithIdentifier:#"Cell"];
if (cell == nil) {
cell = [[[UITableViewCell alloc]
initWithStyle:UITableViewCellStyleValue1
reuseIdentifier:#"Cell"] autorelease];
cell.backgroundColor = [UIColor greenColor];
}
// Configure the cell...
}
Question: how can I change color at start and end of tableView cell? Now the cell is transparent in those areas and displays self.view.backgroundColor from below the whole tableView. Those areas really are transparent, since textured background remains in same location, when scrolling tableView.
set tableView Background as clear color like this,
- (UITableViewCell *)tableView:(UITableView *)tableView
cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
[tableView setBackgroundColor:[UIColor clearColor]];//Here you can give as yellow instead of adding view
//ur code
}
I don't know why you add subview to tableview, you can set the background color for tableview:
tview.backgroundColor=[UIColor yellowColor];

How to get Transparent Accessory View in UITableViewCell? (w/ Screenshot)

I use a custom UITableViewCell from a nib. The accessory view is a Detail Disclosure Indicator . The problem is that the background color of the UITableViewCell behind the accessory view is not getting rendered (see image / source below). Any clues? Also, here are some things that I tried but did NOT work:
Things that DID NOT work:
- Setting the backgroundColor of the accessory view to clearColor
- Setting the contentView.opaque of the cell to FALSE
- Setting the contentView.opaque of the Table View to FALSE
- Setting a non-default accessory view for the cell
alt text http://www.chicknchoke.com/so/IMG_8028.png
-(void)showTablePrep
{
myTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 480, 320, 416) style:UITableViewStylePlain];
myTableView.dataSource = self;
myTableView.delegate = self;
myTableView.delaysContentTouches = FALSE;
myTableView.opaque = FALSE;
myTableView.rowHeight = 60;
[UIView beginAnimations:#"SlideUp" context:nil];
[UIView setAnimationDuration:0.3f];
[myTableView setCenter:CGPointMake(myTableView.center.x, myTableView.center.y-436)];
[self.view addSubview:myTableView];
[self.view bringSubviewToFront:myTableView];
[UIView commitAnimations];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
FriendsCell* cell = [tableView dequeueReusableCellWithIdentifier:#"CustomCellID"];
if (cell == nil){
NSArray *nib = [[NSBundle mainBundle] loadNibNamed:#"FriendsCellView" owner:self options:nil];
cell = (FriendsCell*)[nib objectAtIndex:0];
if(indexPath.row % 2 == 0){
cell.contentView.backgroundColor = [UIColor grayColor];
}else{
cell.contentView.backgroundColor = [UIColor lightGrayColor];
}
cell.accessoryView.backgroundColor = [UIColor clearColor];
cell.contentView.opaque = FALSE;
cell.selectionStyle = UITableViewCellSelectionStyleNone;
if(f
riendsCounter > indexPath.row){
cell.titleLabel.text = #"Label";
cell.descLabel.text = #"Description goes here";
}else{
cell.titleLabel.text = #"";
cell.descLabel.text = #"";
cell.accessoryType = UITableViewCellAccessoryNone;
}
}
return cell;
}
You're drawing the background color for your cell incorrectly. A UITableViewCell will be arranged so that the contentView and accessoryView sit side-by-side. (This is done so that the contentView can clip its content so it doesn't overlap with the accessory view) The problem is not that the accessory view is opaque, it's that the gray background is simply not drawn behind the accessory view.
The correct way of customizing the background drawn behind a UITableViewCell is to customize its backgroundView. I haven't tried this, but since you're only changing the color, you might be able to simply set the backgroundColor color on the backgroundView to your desired color.
I found the answer by having a look at the subviews of my custom table view cell.
It seems like the accessory view has a button sitting over it. By finding this button in the subviews and changing its color, i was able to update the background color behind the accessory button.
<UIButton: 0x3b4d690; frame = (277 0; 43 75); opaque = NO; layer = <CALayer: 0x3b3e0b0>>
for (UIView *aSubView in self.subviews) {
if ([aSubView isMemberOfClass:[UIButton class]]) {
aSubView.backgroundColor = [UIColor greenColor];
}
}
Unfortunately I was only able to reach this button within the
- (void)setSelected:(BOOL)selected animated:(BOOL)animated
method of my custom table view cell class. I've used this successfully within my app to display a different highlight color when the user selects a cell. This should point you in the right direction.
I resolve this problem on iOS7 but adding
[cell setSelectionStyle:UITableViewCellSelectionStyleNone];
in
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
and you modify your background and other bakcgrounds here :
- (BOOL)tableView:(UITableView *)tableView shouldHighlightRowAtIndexPath:(NSIndexPath *)indexPath {
return YES;
}
- (void)tableView:(UITableView *)tableView didHighlightRowAtIndexPath:(NSIndexPath *)indexPath {
// Add your Colour.
UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
[cell setBackgroundColor:[UIColor colorWithHexColor:HIGHLIGHT_COLOR]];
}
- (void)tableView:(UITableView *)tableView didUnhighlightRowAtIndexPath:(NSIndexPath *)indexPath {
// Reset Colour.
UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
[cell setBackgroundColor:[UIColor colorWithHexColor:UNHIGHLIGHT_COLOR]];
}

How do I set UITableViewCellSelectionStyle property to some custom color?

I am developing an iPhone application, in my table view I wanted custom color for Cell Selection Style, I read the UITableViewCell Class Reference but there are only three constants defined for Selection style (Blue, Gray, None). I saw one application that used a different color than those defined in the reference.
How can we use a color other than those defined in the reference?
The best way to set the selection is to set the selectedBackgroundView on the cell when you construct it.
i.e.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:CellIdentifier] autorelease];
cell.selectedBackgroundView = [[[UIImageView alloc] initWithImage:[UIImage imageNamed:#"SelectedCellBackground.png"]] autorelease];
}
// configure the cell
}
The image used should have a nice gradient (like the default selection). If you just want a flat color, you can use a UIView instead of a UIImageView and set the backgroundColor to the color you want.
This background is then automatically applied when the row is selected.
Setting the selectedBackgroundView seems to have no effect when the cell.selectionStyle is set to UITableViewCellSelectionStyleNone. When I don't set the style is just uses the default gray.
Using the first suggestion that inserts the custom UIView into the cell does manipulate the cell but it doesn't show up when the cell is touched, only after the selected action is completed which is too late because I'm pushing to a new view. How do I get the selected view in the cell to display before the beginning of the selected operation?
If you have subclassed a UITableViewCell, then you can customise the various elements of the cell by overriding the following:
- (void)setHighlighted:(BOOL)highlighted animated:(BOOL)animated {
if(highlighted) {
self.backgroundColor = [UIColor redColor];
} else {
self.backgroundColor = [UIColor clearColor];
}
[super setHighlighted:highlighted animated:animated];
}
EDIT for iOS7:
as Sasho stated, you also need
cell.selectionStyle = UITableViewCellSelectionStyleNone
I tried some of the above, and I actually prefer to create my own subclass of UITableViewCell and then override the touchesBegan/touchesCancelled/touchesEnded methods. To do this, ignore all the selectedBackgroundView and highlightedColor properties on the cell, and instead just set these colors manually whenever one of the above methods are called. For example, if you want to set the cell to have a green background with red text, try this (within your custom cell subclass):
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
//Set backgorund
self.backgroundColor = [UIColor themeBlue];
//Set text
self.textLabel.textColor = [UIColor themeWhite];
//Call super
[super touchesBegan:touches withEvent:event];
}
Note that for this to work, you need to set:
self.selectionStyle = UITableViewCellSelectionStyleNone;
Otherwise, you'll first get the current selection style.
EDIT:
I suggest using the touchesCancelled method to revert back to the original cell colors, but just ignore the touchesEnded method.
Override didSelectRowAtIndexPath: and draw a UIView of a color of your choosing and insert it behind the UILabel inside the cell. I would do it something like this:
UIView* selectedView; //inside your header
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
UITableViewCell* cell = [tableView cellForRowAtIndexPath:indexPath];
selectedView = [[UIView alloc] initWithFrame:[cell frame]];
selectedView.backgroundColor = [UIColor greenColor]; //whatever
[cell insertSubview:selectedView atIndex:0]; //tweak this as necessary
[selectedView release]; //clean up
}
You can choose to animate this view out when it gets deselected and will satisfy your requirements.
Sublcass UITableViewCell and override setHighlighted:animated:
You can define a custom selection color color by setting the backgroundColor (see WIllster's answer):
- (void)setHighlighted:(BOOL)highlighted animated:(BOOL)animated {
if(highlighted) {
self.backgroundColor = [UIColor redColor];
} else {
self.backgroundColor = [UIColor clearColor];
}
[super setHighlighted:highlighted animated:animated];
}
You can define a custom background image by setting the backgroundView property:
- (void)setHighlighted:(BOOL)highlighted animated:(BOOL)animated {
if( highlighted == YES )
self.backgroundView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:#"seasonal_list_event_bar_default.png"]];
else
self.backgroundView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:#"seasonal_list_event_bar_active.png"]];
[super setHighlighted:highlighted animated:animated];
}
- (void)setHighlighted:(BOOL)highlighted animated:(BOOL)animated {
// Set Highlighted Color
if (highlighted) {
self.backgroundColor = [UIColor colorWithRed:234.0f/255 green:202.0f/255 blue:255.0f/255 alpha:1.0f];
} else {
self.backgroundColor = [UIColor clearColor];
}
}
- (BOOL)tableView:(UITableView *)tableView shouldHighlightRowAtIndexPath:(NSIndexPath *)indexPath {
return YES;
}
- (void)tableView:(UITableView *)tableView didHighlightRowAtIndexPath:(NSIndexPath *)indexPath {
// Add your Colour.
SocialTableViewCell *cell = (SocialTableViewCell *)[tableView cellForRowAtIndexPath:indexPath];
[self setCellColor:Ripple_Colour ForCell:cell]; //highlight colour
}
- (void)tableView:(UITableView *)tableView didUnhighlightRowAtIndexPath:(NSIndexPath *)indexPath {
// Reset Colour.
SocialTableViewCell *cell = (SocialTableViewCell *)[tableView cellForRowAtIndexPath:indexPath];
[self setCellColor:Ripple_Colour ForCell:cell]; //normal color
}
- (void)setCellColor:(UIColor *)color ForCell:(UITableViewCell *)cell {
cell.contentView.backgroundColor = color;
cell.backgroundColor = color;
}
To add a custom color use the below code. And to make it transparent use alpha: 0.0
cell.selectedBackgroundView = UIView(frame: CGRect.zero)
cell.selectedBackgroundView?.backgroundColor = UIColor(red:0.27, green:0.71, blue:0.73, alpha:1.0)
If you use custom color and want to give it rounded corner look use:
cell.layer.cornerRadius = 8
Also, use this for better animation and feel
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
}