can't change UITableViewCell background color - iphone

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

Related

Setting Position of the textlabel inside the tableviewcell?

In my application i am trying to adjust the position of the textlabel and detailtextlabel in a tableview cell.I am doing like this `
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier] autorelease];
UIImageView* img = [[UIImageView alloc]initWithImage:[UIImage imageNamed:#"cell_with_arrow.png"]];
[cell setBackgroundView:img];
[img release];
}
cell.textLabel.frame = CGRectMake(0,0, 150, 40);
cell.detailTextLabel.frame = CGRectMake(155, 55, 150, 40);
cell.textLabel.font = [UIFont fontWithName:#"Helvetica-Bold" size:14.0];
cell.textLabel.textColor = [UIColor blackColor];
cell.textLabel.backgroundColor = [UIColor clearColor];
cell.textLabel.text =#"name";
cell.detailTextLabel.text=#" status";
cell.detailTextLabel.backgroundColor = [UIColor clearColor];
//cell.detailTextLabel.textAlignment = UITextAlignmenteft;
//cell.textLabel.textAlignment = UITextAlignmentLeft;
return cell;
}
`but seems to be having no effect.can anybody help me to point me where i am going wrong?
textLabel and detailTextLabel are readonly so you can not change them.
#property(nonatomic, readonly, retain) UILabel *textLabel
#property(nonatomic, readonly, retain) UILabel *detailTextLabel
See here
What I would suggest is that you could create your custom UITableViewCell instead, you will have more control over it's content and can add custom subviews in there as well.
Here are some tutorials for that:
From IB
From Code
you need to override layoutSubviews method
Create a customcell class and inherit with uitableviewcell
#try this code
CustomCell.h
#import <UIKit/UIKit.h>
#interface CustomCell : UITableViewCell
#end
CustomCell.m
#import "CustomCell.h"
#implementation CustomCell
- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
if (self) {
// Initialization code
}
return self;
}
-(void)layoutSubviews{
//Set here your frame
self.textLabel.frame = CGRectMake(0, , 320, 30);
}
- (void)setSelected:(BOOL)selected animated:(BOOL)animated
{
[super setSelected:selected animated:animated];
// Configure the view for the selected state
}
#end

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

Change gradient of background color with respect to UISlider value placed into TableViewCell

i am new to objective C. I want to Change the gradient of background color of a Lable placed in the Cell
with respect to the UIslider placed in same cell.
As the slider moves from Left to Right the gradient of the Background color should change.
Can anyone guide me how to do it???
This code will change alpha of background color of UILabel as per slider value change.
first you need to declare slider in custom Cell. as describe bellowed.
Declare slider in SignUpCustomCell.h cell.
#import <UIKit/UIKit.h>
#interface SignUpCustomCell : UITableViewCell {
UISlider* slider;
UILabel *lblLeft;
}
#property(nonatomic,retain) UISlider* slider;
#property(nonatomic,retain) UILabel *lblLeft;
#end
alloc memory in SignUpCustomCell.m file.
#import "SignUpCustomCell.h"
#synthesize slider,lblLeft;
- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier {
if ((self = [super initWithStyle:style reuseIdentifier:reuseIdentifier])) {
slider=[[UISlider alloc]initWithFrame:CGRectMake(150, 5, 100, 25)];
[slider setValue:0.0];
slider.minimumValue=0;
slider.maximumValue=1;
[self.contentView addSubview:self.slider];
self.lblLeft = [[UILabel alloc]init];
self.lblLeft.font = [UIFont fontWithName:#"Helvetica-Bold" size:12];
self.lblLeft.textColor = [UIColor colorWithRed:135.0/255.0 green:135.0/255.0 blue:135.0/255.0 alpha:1.0];
self.lblLeft.backgroundColor = [UIColor greenColor];
[self.lblLeft setTextAlignment:UITextAlignmentLeft];
[self.contentView addSubview:self.lblLeft];
[self.lblLeft release];
}
return self;
}
After creating custom cell.You will used it where you want.
To used custome cell in SignupViewController.m . we need following steps.
#import "SignUpCustomCell.h"
Then write code in cellForRowAtIndexPath.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
SignUpCustomCell *cell = (SignUpCustomCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil)
{
cell = [[[SignUpCustomCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
}
cell.lblLeft.text=#"test app";
cell.slider.tag=indexPath.row;
[cell.slider addTarget:self action:#selector(sliedervalue:) forControlEvents:UIControlEventValueChanged];
return cell;
}
-(void)sliedervalue:(id)sender
{
UISlider* sl=(UISlider*)sender;
NSLog(#"sl=%d",sl.tag);
NSLog(#"sl_value=%f",sl.value);
NSIndexPath *indexPath=[NSIndexPath indexPathForRow:sl.tag inSection:0] ;
SignUpCustomCell *cell = (SignUpCustomCell*)[tblSignup cellForRowAtIndexPath:indexPath];
cell.lblLeft.alpha= sl.value;
}
Let me know if you have any query.

How can we add button in custom cell?

I am working in a app and need to add button in cell by customcell.
Can any one help me for this?
Thanks in advance
You add a button in Customcell so use the following code.
First of all , you add new file with subclass of UITableViewCell and then
Customcell.h file
#interface CustomCell : UITableViewCell
{
UIButton *customButton;
}
#property (nonatomic , retain) UIButton *customButton;
Customcell.m
#implementation CustomCell;
#synthesize customButton;
- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
if ((self = [super initWithStyle:style reuseIdentifier:reuseIdentifier]))
{
customButton = [UIButton buttonWithType:UIButtonTypeCustom];
[customButton setImage:[UIImage imageNamed:#"phonecall.png"] forState:UIControlStateNormal];
}
return self;
}
// set layout in subview
- (void)layoutSubviews
{
[super layoutSubviews];
CGRect contentRect = self.contentView.bounds;
CGFloat boundsX = contentRect.origin.x;
CGFloat boundY = contentRect.origin.y;
CGRect frame1;
frame1 = CGRectMake(boundsX+10, boundY+58, 19, 18);
customButton.frame = frame1;
}
#import "CustomCell.h"
In cellForRowAtIndexPath method
// Customize the number of cells in the table view.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
CustomCell *cell= [[[CustomCell alloc] initWithFrame:CGRectZero reuseIdentifier:CellIdentifier] autorelease];
if (cell == nil)
{
cell = [[[CustomCell alloc] initWithFrame:CGRectZero reuseIdentifier:CellIdentifier] autorelease];
}
[cell.customButton addTarget:self action:#selector(callAction:) forControlEvents:UIControlEventTouchUpInside];
return cell;
}

UITableView scrolling changess image inside UITableViewCell

I am displaying some data using a UITableViewController, my table has 2 static sections with 6 static rows each. And I am subclassing UITableViewCell in order to add 3 Labels and a View, in the view I draw an arrow in only one of the cells in one of the sections.
This all goes perfectly fine. Till i scroll down... then the arrow is randomly placed in other cells, once i scroll back up the arrow has again changed cells... This also happens if i try to set a backgroundColor for only one of the cells. Once I scroll down and up the cell that originally had the color no longer has it, and another seemingly random cell has the color now.
Here is some of my code:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"Cell";
TableViewCells *cell = (TableViewCells *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[TableViewCells alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
}
[self configureCell:cell atIndexPath:indexPath];
return cell;
}
- (void)configureCell:(TableViewCells *)cell atIndexPath:(NSIndexPath *)indexPath {
switch (indexPath.row) {
case 0:
{
if (indexPath.section == cotizacionIdeal)
{
cell.arrowImage = [UIImage imageNamed:#"arrowUp.png"];
[cell.nombre setText:#"Recursos"];
[cell.cantidad setText:[NSString stringWithFormat:#"%1.2f", [cotizacionPrevia.sueldoDeRecursos doubleValue]]];
[cell.porcentaje setText:[NSString stringWithFormat:#"%1.2f%#", [cotizacion.recursosPorcentaje doubleValue], #"%"]];
}
else
{
[cell.nombre setText:#"Recursos"];
[cell.cantidad setText:[NSString stringWithFormat:#"%1.2f", [cotizacionPrevia.sueldoDeRecursos doubleValue]]];
[cell.porcentaje setText:[Calculate calcPorcentaje:cotizacionPrevia.sueldoDeRecursos totalReal:self.totalReal]];
}
}
break;
case 1:
{
if (indexPath.section == cotizacionIdeal)
{
[cell.nombre setText:#"Comision de Venta"];
[cell.cantidad setText:[Calculate calcMonto:cotizacion.comisionPorcentaje total:self.totalIdeal]];
[cell.porcentaje setText:[NSString stringWithFormat:#"%1.2f%#", [cotizacion.comisionPorcentaje doubleValue], #"%"]];
}
else
{
[cell.nombre setText:#"Comision de Venta"];
[cell.cantidad setText:self.montoRealComision];
[cell.porcentaje setText:[NSString stringWithFormat:#"%1.2f%#", [cotizacion.comisionPorcentaje doubleValue], #"%"]];
}
}
UITableViewCell class:
- (id)initWithFrame:(CGRect)frame cell:(TableViewCells *)cell
{
if (self = [super initWithFrame:frame]) {
_cell = cell;
//self.opaque = YES;
//self.backgroundColor = _cell.backgroundColor;
}
return self;
}
- (void)drawRect:(CGRect)rect
{
[_cell.arrowImage drawAtPoint:CGPointMake(0, 0)];
}
#end
#implementation TableViewCells
#synthesize nombre;
#synthesize porcentaje;
#synthesize cantidad;
#synthesize arrowImage;
- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier {
if (self = [super initWithStyle:style reuseIdentifier:reuseIdentifier]) {
// Initialization code
UILabel *nombreLabel = [[UILabel alloc] initWithFrame:CGRectZero];
self.nombre = nombreLabel;
[nombreLabel release];
[self.nombre setFont:[UIFont boldSystemFontOfSize:14]];
[self.contentView addSubview:self.nombre];
UILabel *porcentajeLabel = [[UILabel alloc] initWithFrame:CGRectZero];
self.porcentaje = porcentajeLabel;
[porcentajeLabel release];
[self.porcentaje setFont:[UIFont italicSystemFontOfSize:10]];
[self.contentView addSubview:self.porcentaje];
UILabel *cantidadLabel = [[UILabel alloc] initWithFrame:CGRectZero];
self.cantidad = cantidadLabel;
[self.cantidad setTextAlignment:UITextAlignmentRight];
[cantidadLabel release];
[self.cantidad setFont:[UIFont boldSystemFontOfSize:14]];
[self.contentView addSubview:self.cantidad];
cellContentView = [[TableViewCellContentView alloc] initWithFrame:CGRectZero cell:self];
cellContentView.backgroundColor = [UIColor clearColor];
[self.contentView addSubview:cellContentView];
}
UPDATE:
I have also tried setting the image to a different one for everyone but one and I am still having the same issue.
- (void)configureCell:(TableViewCells *)cell atIndexPath:(NSIndexPath *)indexPath {
cell.arrowImage = [UIImage imageNamed:#"arrowDown.png"];
switch (indexPath.row) {
case 0:
{
if (indexPath.section == cotizacionIdeal)
{
cell.arrowImage = [UIImage imageNamed:#"arrowUp.png"];
[cell.nombre setText:#"Recursos"];
[cell.cantidad setText:[NSString stringWithFormat:#"%1.2f", [cotizacionPrevia.sueldoDeRecursos doubleValue]]];
[cell.porcentaje setText:[NSString stringWithFormat:#"%1.2f%#", [cotizacion.recursosPorcentaje doubleValue], #"%"]];
}
else
{
The problem is that whenever you use drawRect for a cell you MUST call setneedsdisplay. That is what fixed my problem.
The issue is that the UITableView reuses cells so that it doesn't need to make more instances than are displayed and you're not explicitly removing the arrow in your configureCell method.
If the arrow shouldn't be displayed on a cell, explicitly clear it out in the configureCell method and that should fix it.
I am not 100% on this but I think it is to do with the release of the image. When you use imageNamed, the instance is retained so it is suggested to use imageWithFilePath instead.
Hope this helps....