Custom cell with overlapping cells - iphone

I´m using the method cellForRowAtIndexPath to draw cells with 2 labels. When i reuse a cell the label i had before in that cell isn´t erased, so i get two labels overlapping because i´m reusing a cell. This is weird cause only the label title gets overlapped, the other doesn´t.
So what i did to fix this, is that i´m always creating a new cell. Which isn´t appropriate but solves the problem... Anyone had a similar bug and manage to fix it? Cause i just made a workaround...
//Desenhado por codigo
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell;
UILabel *label = nil;
UILabel *label2 = nil;
UIColor *green = [UIColor colorWithRed:0 green: 0.77 blue:0 alpha:1];
cell = [tableView dequeueReusableCellWithIdentifier:#"Cell"];
// if (cell == nil)
{
cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:#"Cell"] autorelease];
//Descrição
label = [[UILabel alloc] initWithFrame:CGRectZero];
[label setLineBreakMode:UILineBreakModeWordWrap];
[label setMinimumFontSize:FONT_SIZE];
[label setNumberOfLines:0];
[label setFont:[UIFont systemFontOfSize:FONT_SIZE]];
[label setFont:[UIFont fontWithName:#"HelveticaNeue-CondensedBold" size:14.0]];
[label setTag:1];
[label setTextColor:green];
[label setBackgroundColor:[UIColor clearColor]];
label.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:#"barra_cinza_lista.png"]];
[[cell contentView] addSubview:label];
label2 = [[UILabel alloc] initWithFrame:CGRectZero];
[label2 setLineBreakMode:UILineBreakModeWordWrap];
[label2 setMinimumFontSize:FONT_SIZE];
[label2 setNumberOfLines:0];
[label2 setFont:[UIFont systemFontOfSize:FONT_SIZE]];
[label2 setFont:[UIFont fontWithName:#"HelveticaNeue-CondensedBold" size:14.0]];
[label2 setTag:2];
[label2 setTextColor:[UIColor whiteColor]];
[label2 setBackgroundColor:[UIColor clearColor]];
[[cell contentView] addSubview:label2];
}
NSString *text = [self getTableViewRow:tableView index:indexPath];
NSString *title = #" %#";
if(tableView == myTableView1)
title = [NSString stringWithFormat:title, [_titlesResults objectAtIndex:indexPath.row]];
else
title = [NSString stringWithFormat:title, [_titlesVision objectAtIndex:indexPath.row]];
CGFloat widthMax = CELL_CONTENT_WIDTH - (CELL_CONTENT_MARGIN * 2);
CGSize constraint = CGSizeMake(widthMax, 20000.0f); //Tamanho máximo permitido de largura e altura
CGSize size1 = [title sizeWithFont:[UIFont systemFontOfSize:FONT_SIZE] constrainedToSize:constraint lineBreakMode:UILineBreakModeWordWrap]; //Tamanho ocupado pelas letras
CGSize size2 = [text sizeWithFont:[UIFont systemFontOfSize:FONT_SIZE] constrainedToSize:constraint lineBreakMode:UILineBreakModeWordWrap]; //Tamanho ocupado pelas letras
if (!label)
label = (UILabel*)[cell viewWithTag:1];
if (!label2)
label2 = (UILabel*)[cell viewWithTag:2];
[label setText:title];
[label setFrame:CGRectMake(0, 0, 320, MAX(size1.height, 44.0f))];
[label2 setText:text];
[label2 setFrame:CGRectMake(CELL_CONTENT_MARGIN, 3 * CELL_CONTENT_MARGIN + size1.height, widthMax, MAX(size2.height, 44.0f))];
return cell;
}

At the beginning of the method, enumerate through all the UIView objects in [cell.contentView subviews] and get rid of them, like so:
for (UIView *subview in [cell.contentView subviews]) {
[subview removeFromSuperview];
}
This works because all UI elements inherit from UIView and thus can be removed as if they were.

first, uncomment this line:
// if (cell == nil)
if you don't, you are simply creating and allocating a new cell every time you scroll, and never release the old ones...

Related

UILabels complete text not visible

I have to place two UILabels(state,zipCode) side by side i.e California 32320 in UITableView's cell.I can see them clearly when the fontsize is less.When I increase the font-size I couldnot see the last letter of state label and zipCode label is getting added.This is the code I m working on:
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier=#"Cell";
UITableViewCell* cell=[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if(cell == nil)
{
cell = [[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier]autorelease];
state=[[UILabel alloc] initWithFrame:CGRectZero];
state.tag = 116;
state.backgroundColor = [UIColor clearColor];
[state setFont:[UIFont fontWithName:#"Helvetica-Bold" size:12]];
[state setLineBreakMode:UILineBreakModeWordWrap];
[cell addSubview:state];
zipCode=[[UILabel alloc] initWithFrame:CGRectZero];
zipCode.tag = 121;
zipCode.backgroundColor = [UIColor clearColor];
[zipCode setFont:[UIFont fontWithName:#"Helvetica-Bold" size:12]];
[zipCode setLineBreakMode:UILineBreakModeWordWrap];
[cell addSubview:zipCode];
}
NSString *state1=[d objectForKey:#"State"];
CGSize constraint6=CGSizeMake(175,2000.0f);
CGSize size6=[state1 sizeWithFont:[UIFont fontWithName:#"Helvetica" size:12] constrainedToSize:constraint6 lineBreakMode:UILineBreakModeWordWrap];
state=(UILabel *)[cell viewWithTag:116];
state.frame=CGRectMake(105, city.frame.size.height+city.frame.origin.y+5, size6.width, 10);
[state setTextAlignment:UITextAlignmentLeft];
[state setText:[d valueForKey:#"State"]];
NSString *zip = [d objectForKey:#"Zip"];
if([zip isEqualToString:#""])
{
zipCode=[[UILabel alloc]initWithFrame:CGRectMake(105, 125, 320,10)];
zipCode .font=[UIFont fontWithName:#"Helvetica" size:12];
[zipCode setTextAlignment:UITextAlignmentLeft];
zipCode.hidden=YES;
[zipCode release];
}
else
{
NSString *zip=[d objectForKey:#"Zip"];
CGSize constraint200=CGSizeMake(175,2000.0f);
CGSize size200=[zip sizeWithFont:[UIFont fontWithName:#"Helvetica" size:12] constrainedToSize:constraint200 lineBreakMode:UILineBreakModeWordWrap];
zipCode=(UILabel *)[cell viewWithTag:121];
zipCode.frame=CGRectMake(13+state.frame.size.width+state.frame.origin.x, city.frame.size.height+city.frame.origin.y+5, size200.width,10);
[zipCode setTextAlignment:UITextAlignmentLeft];
[zipCode setText:[d valueForKey:#"Zip"]];
zipCode.numberOfLines=0;
}
return cell;
}
Now I can see the result as
Californi 32320
But when I reduce the font-size to 10 then I can clearly see them (California 32320).But I need the font-size to be 12 only as per my requirement.
Where I m going wrong?
Use this code it will saw the label in fit to size of your label
label.adjustsFontSizeToFitWidth = YES;
Please update the Label width with some what large. And use the "setNoOfLine" property of Lable to 2. So that, it will display text in 2 lines.
Hope it will be helpful to you.
Cheers!
There is a little trick by which the label will auto resize according to your text
UILabel *testLabel = [[UILabel alloc]initWithFrame:CGRectMake(0,0,200,40)];//set your frame
testLabel.numberOfLines = 0;//Important to add this line
testLabel.font = [UIFont boldSystemFontOfSize:15];//Set your font
testLabel.text = #"Set your text here!";
[testLabel sizeToFit]; // this line will do the trick :)
The font of your state label is Helvetica-Bold, but in your sizeWithFont, the font you specified is Helvetica. Alternatively, you can just specify state.font.
Do like this,
CGFloat lLabelWidth = [yourText sizeWithFont: factLabel.font].width;
CGRect _tempFrame=yourLabel.frame;
_tempFrame.size.width=lLabelWidth;
yourLabel.frame=_tempFrame;
hope it will helps you....

how to change label text in custom cell when button in that cell clicked

I have created a custom tableView with labels and buttons. On a button click in a cell i want to change the label text in that cell only. My problem is when i click button corresponding labels in other cell also changes. Here is my code
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
static NSString *CellIdentifier=#"CellIdentifier";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier: CellIdentifier];
if (cell == nil) { cell = [[[UITableViewCell alloc]
initWithStyle:UITableViewCellStyleDefault
reuseIdentifier: CellIdentifier] autorelease];
UILabel *labelOne = [[UILabel alloc]initWithFrame:CGRectMake(70, 10, 100, 20)];
labelOne.tag = 100;
labelOne.backgroundColor=[UIColor clearColor];
labelOne.font=[UIFont systemFontOfSize:14];
[cell.contentView addSubview:labelOne];
[labelOne release];
UIButton *minusbutton=[[UIButton alloc]initWithFrame:CGRectMake(152, 5, 15, 20)];
minusbutton.backgroundColor=[UIColor clearColor];
[minusbutton addTarget:self action:#selector(DecreaseTickets:) forControlEvents:UIControlEventTouchUpInside];
[minusbutton setTitle:#"-" forState:UIControlStateNormal];
[minusbutton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
[minusbutton setBackgroundImage:[UIImage imageNamed:#"button-green1.png"] forState:UIControlStateNormal];
[cell.contentView addSubview:minusbutton];
[minusbutton release];
UILabel *quantity = [[UILabel alloc]initWithFrame:CGRectMake(170, 5, 20, 20)];
quantity.tag = 103;
quantity.backgroundColor=[UIColor clearColor];
quantity.font=[UIFont systemFontOfSize:12];
[cell.contentView addSubview:quantity];
[quantity release];
UIButton *addbutton=[[UIButton alloc]initWithFrame:CGRectMake(192, 5, 15, 20)];
addbutton.backgroundColor=[UIColor clearColor];
[addbutton addTarget:self action:#selector(IncreaseTickets:) forControlEvents:UIControlEventTouchUpInside];
[addbutton setTitle:#"+" forState:UIControlStateNormal];
[addbutton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
[addbutton setBackgroundImage:[UIImage imageNamed:#"button-green1.png"] forState:UIControlStateNormal];
[cell.contentView addSubview:addbutton];
[addbutton release];
UILabel *labelTwo = [[UILabel alloc]initWithFrame:CGRectMake(260, 10, 140, 20)];
labelTwo.tag = 101;
labelTwo.backgroundColor=[UIColor clearColor];
labelTwo.font=[UIFont systemFontOfSize:14];
labelTwo.textColor=[UIColor colorWithRed:0.25098 green:0.447059 blue:0.07451 alpha:1];
[cell.contentView addSubview:labelTwo];
[labelTwo release];
UILabel *label3 = [[UILabel alloc]initWithFrame:CGRectMake(70, 30, 230, 30)];
label3.tag = 102;
label3.backgroundColor=[UIColor clearColor];
label3.numberOfLines=2;
label3.font=[UIFont systemFontOfSize:12];
[cell.contentView addSubview:label3];
[label3 release];
}
UILabel *labelOne = (UILabel *) [cell.contentView viewWithTag:100];
NSString *ss2=[[NSString alloc]initWithFormat:#"%#",[[eventTicketListArray objectAtIndex:indexPath.row ]tit] ];
labelOne.text = ss2;
UILabel *labelTwo = (UILabel *) [cell.contentView viewWithTag:101];
labelTwo.text = [[NSString alloc]initWithFormat:#"%#",[[eventTicketListArray objectAtIndex:indexPath.row ]price] ];
UILabel *label3 = (UILabel *) [cell.contentView viewWithTag:102];
label3.text=[[NSString alloc]initWithFormat:#"%#",[[eventTicketListArray objectAtIndex:indexPath.row ]desc ] ];
UILabel *label4 = (UILabel *) [cell.contentView viewWithTag:103];
label4.text=[[NSString alloc]initWithFormat:#"%d",qty];
}
return cell;
}
Initially qty=0
now i want that when i click addbutton, qty of that cell increases. here is my button click event
-(void)IncreaseTickets:(id)sender{
NSIndexPath *indexPath =[ticketTable indexPathForCell:(UITableViewCell *)[[sender superview] superview]];
//NSUInteger row = indexPath.row;
UITableViewCell *currentCell = (UITableViewCell *)[[sender superview] superview] ;
UILabel *label4 = (UILabel *) [currentCell.contentView viewWithTag:103];
label4.text=[[[NSString alloc]initWithFormat:#"%d",qty++] ;
//NSLog(#"%d",row);
[ticketTable reloadData];
}
But the problem is when i click the button,qty of all cell increases. Please guide me how to do it. Any help will be appreciated.
Set condition like this..
set on global Variable NSUInteger myRow.
myRow = indexPath.row;//Set Selected index path.
in cellForRowAtIndexPath set condition.
if(myRow == indexPath.row)
{
NSUInteger newqty = qty + 1;
UILabel *label4 = (UILabel *) [cell.contentView viewWithTag:103];
label4.text=[[NSString alloc]initWithFormat:#"%d",newqty];
}
esle
{
UILabel *label4 = (UILabel *) [cell.contentView viewWithTag:103];
label4.text=[[NSString alloc]initWithFormat:#"%d",qty];
}
and set some logic for that.
when you call
[ticketTable reloadData];
all your data reload and your table is initialized again
UITable magic is in reuse of a few allocated cells (just the minimus number of cell required: the viewable cells in a time on screen) and then you should just reuse them with new data setting when you scroll, typically using NSArray in your table data delegate...
and: where qty is defined? it seems it's a global variable, not one for every single cell...
you'd better to read some apple example code or some tutorial

Unable to fetch the value from UITableViewCell by the self define methods

I am creating an app in which i have a UITableView and the table view each cell are having an UIView and the UIView contains two custom UIButton and two UILabel(all with same tag) the value of label coming from XML parsing. Now i have to do is that when i click any one button then it calls a method with the tag of the button then i want to fetch the value of the both labels of that cell and use that value.
But when i am doing this it is not happen by calling a method i am getting the tag value but when i try to get the label value then i am unable to get.
Is there any way to get the value of that?
Code of the method that i am using to get the label value...
-(void)swapButtonPressed:(id)sender {
NSInteger a= [sender tag];
UITableViewCell *cell;
NSIndexPath *indexPath = [self.tableView indexPathForCell:(UITableViewCell *) [[sender superview] superview]];
NSLog(#"%d", indexPath.row);
UIView *viewForCell = (UIView *)[cell.contentView viewWithTag:a];
UILabel *label = (UILabel *)[viewForCell viewWithTag:a];
NSString *str = label.text;
}
Code of the method cellForRowAtIndexPath....
- (UITableViewCell *)tableView:(UITableView *)tableView1 cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *identifier = #"Cell";
UITableViewCell *cell = [tableView1 dequeueReusableCellWithIdentifier:identifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier] autorelease];
}
cell.selectionStyle = UITableViewCellSelectionStyleNone;
NSDictionary *dict = [appDelegate.webDataList objectAtIndex:indexPath.row];
tableView.backgroundColor = [UIColor colorWithRed:0.39 green:0.39 blue:0.39 alpha:0.39];
if([appDelegate.dataArray count]>0){
imgView.backgroundColor = [UIColor clearColor];
imgView =[[UIView alloc ] initWithFrame:CGRectMake(0,0,320,45)];
imgView.tag= indexPath.row;
[cell.contentView addSubview:imgView];
button=[UIButton buttonWithType:UIButtonTypeCustom];
button.frame=CGRectMake(291, 5, 19, 21);
img =[UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:#"swap_re" ofType:#"png"]];
[button setBackgroundImage:img forState:UIControlStateNormal];
[button addTarget:self action:#selector(swapButtonPressed:) forControlEvents:UIControlEventTouchUpInside];
button.tag= indexPath.row;
[imgView addSubview:button];
button=[UIButton buttonWithType:UIButtonTypeCustom];
button.frame=CGRectMake(-25, 5, 19, 21);
img =[UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:#"swap_re" ofType:#"png"]];
[button setBackgroundImage:img forState:UIControlStateNormal];
[button addTarget:self action:#selector(swapButtonPressed:) forControlEvents:UIControlEventTouchUpInside];
button.tag= indexPath.row;
[imgView addSubview:button];
button=[UIButton buttonWithType:UIButtonTypeCustom];
button.frame=CGRectMake(5, 7, 19, 21);
button.tag = indexPath.row;
img =[UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:#"delete" ofType:#"png"]];
[button setBackgroundImage:img forState:UIControlStateNormal];
[button addTarget:self action:#selector(deleteButtonPressed:) forControlEvents:UIControlEventTouchUpInside];
[imgView addSubview:button];
NSArray *arr = [[appDelegate.dataArray objectAtIndex:indexPath.row] componentsSeparatedByString:#"/"];
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(34,9,140,20)];
label.text = [arr objectAtIndex:1];
label.tag = indexPath.row;
[label setFont:[UIFont fontWithName:#"Georgia" size:14]];
[label setNumberOfLines:0];
label.textAlignment = UITextAlignmentLeft;
label.textColor = [UIColor whiteColor];
label.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleHeight;
label.backgroundColor = [UIColor clearColor];
[imgView addSubview:label];
[label release];
label = [[UILabel alloc] initWithFrame:CGRectMake(181, 7, 75, 20)];
label.tag = indexPath.row;
label.text = [dict1 objectForKey:#"time"];
[label setFont:[UIFont fontWithName:#"Georgia" size:16.0]];
label.textAlignment = UITextAlignmentLeft;
[label setBackgroundColor:[UIColor clearColor]];
label.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleHeight;
[label setTextColor:[UIColor whiteColor]];
[imgView addSubview:label];
[label release];
}
return cell;
}
I see two problems:
Tags need to be > 0 so you can't use indexPath.row directly.
Tags need to be unique within a superview
As #Kenny suggests, getting the indexPath from the cell and accessing the data source directly is generally more reliable. If you want to get values from the objects in the cell use unique tags > 0. I usually define an enum for tags within a subview to make things more readable.
I think that viewWithTag is recursive, so in your code that would mean that you get the label back in the first call to it, and nil in the second call. So perhaps this would work:
UILabel *label = (UILabel *)[cell.contentView viewWithTag:a];
NSString *str = label.text;
However, I'd recommend you get the value from your model object where you probably got it when you set the string on the button in the first place, something like this:
NSIndexPath *indexPath = [self.tableView indexPathForCell:(UITableViewCell *) [[sender superview] superview]];
TheObect *obj = [myobjects objectAtIndex:indexPath.row];
NSString *string = obj.name;

UITableView Cell is regenerating

I have UITableViewCell with UILabel and UISwitch. By default all UISwitch is set to off.
Once I will turn on the switch and then scroll through table the switch value is set to default again,i.e.Off
Below is the code which I have used:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if(cell != nil) cell = nil;
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
}
if (indexPath.row == 0) {
UILabel *lbl1 = [[UILabel alloc] initWithFrame:CGRectMake(20, 10, 100, 30)];
lbl1.text = #"Some Text";
[cell addSubview:lbl1];
switch = [[UISwitch alloc] initWithFrame:CGRectMake(190, 10, 200, 30)];
[switch setOn:NO];
switch.tag = 1;
[switch addTarget:self action:#selector(switchTapped:) forControlEvents:UIControlEventChanged];
[cell addSubview:switch];
}
}
// Below is my switchTapped method:
- (void) switchTapped: (id)sender {
UISwitch *tapSwitch = (UISwitch *)sender;
switch (tapSwitch.tag) {
case 1:
if (tapSwitch.on) {
// do something
}
else {
// do something
}
break;
case 2:
if (tapSwitch.on) {
// do something
}
else {
// do something
}
break;
}
Am I doing anything wrong over here?
Thank You.
You're using really nasty code which regenerates the cell each time it's needed:
if(cell != nil)
{
cell = nil;
}
if (cell == nil)
{
...
}
Do you bind the state of your switch to some retained object (e.g. Item model object, where single cell reflects an Item)?
This is how I write my cell drawing code:
Basically, within my if(cell == nil) { ... } I do all the "initWithFrame". Anything outside that, I simply set the value such as label text. Don't do the initWithFrame outside the if(cell == nil) {...} block of code.
-(UITableViewCell *) tableView:(UITableView *) tableView cellForRowAtIndexPath:(NSIndexPath *) indexPath
{
static NSString *reusableCell = #"reusableCell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reusableCell];
if(cell == nil)
{
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:reusableCell] autorelease];
thumbnail = [[UIImageView alloc] initWithFrame:CGRectMake(5, 5, 106, 81)];
feedTitle = [[UILabel alloc] initWithFrame:CGRectMake(116, 3, [IOSDevice screenWidth] - 140, 25)];
postDate = [[UILabel alloc] initWithFrame:CGRectMake(116, 10, [IOSDevice screenWidth] - 140, 50)];
description = [[UILabel alloc] initWithFrame:CGRectMake(116, 45, [IOSDevice screenWidth] - 140, 50)];
// setting tag reminders so we can identify the element to replace
[thumbnail setTag:1];
[feedTitle setTag:2];
[postDate setTag:3];
[description setTag:4];
[[cell contentView] addSubview:thumbnail];
[[cell contentView] addSubview:feedTitle];
[[cell contentView] addSubview:description];
[[cell contentView] addSubview:postDate];
[thumbnail release];
[feedTitle release];
[description release];
[postDate release];
}
thumbnail = (UIImageView *)[[cell contentView] viewWithTag:1];
feedTitle = (UILabel *)[[cell contentView] viewWithTag:2];
postDate = (UILabel *)[[cell contentView] viewWithTag:3];
description = (UILabel *)[[cell contentView] viewWithTag:4];
[feedTitle setBackgroundColor:[UIColor clearColor]];
[feedTitle setFont:[UIFont fontWithName:#"Helvetica-Bold" size:16]];
[feedTitle setTextColor:[UIColor colorWithRed:0.215 green:0.215 blue:0.215 alpha:1.0]];
[description setBackgroundColor:[UIColor clearColor]];
[description setFont:[UIFont fontWithName:#"Helvetica" size:12]];
[description setTextColor:[UIColor colorWithRed:0.328 green:0.328 blue:0.328 alpha:1.0]];
[description setNumberOfLines:2];
[description setLineBreakMode:UILineBreakModeWordWrap];
[postDate setBackgroundColor:[UIColor clearColor]];
[postDate setFont:[UIFont fontWithName:#"Helvetica" size:12]];
[postDate setTextColor:[UIColor colorWithRed:0.707 green:0.180 blue:0.141 alpha:1.0]];
[thumbnail setImage:[[items objectAtIndex:[indexPath row]] objectForKey:#"thumb"]];
[feedTitle setText:[[items objectAtIndex:[indexPath row]] objectForKey:#"title"]];
[description setText:[[items objectAtIndex:[indexPath row]] objectForKey:#"summary"]];
// Format date
NSDateFormatter *dateFormatter = [[[NSDateFormatter alloc] init] autorelease];
[dateFormatter setDateStyle:NSDateFormatterLongStyle];
[dateFormatter setTimeStyle:NSDateFormatterShortStyle];
[postDate setText:[dateFormatter stringFromDate:[[items objectAtIndex:[indexPath row]] objectForKey:#"date"]]];
[cell setSelectionStyle:UITableViewCellSelectionStyleNone];
[cell setAccessoryType:UITableViewCellAccessoryDisclosureIndicator];
if([feedList contentOffset].y < -50)
{
shouldUpdate = TRUE;
[activityIndicator stopAnimating];
[feedList setContentOffset:CGPointMake(0, -30) animated:NO];
[self loadData];
loadingLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, -25, [IOSDevice screenWidth], 20)];
[loadingLabel setText:#"Loading New Data"];
[loadingLabel setTextAlignment:UITextAlignmentCenter];
[loadingLabel setBackgroundColor:[UIColor clearColor]];
[loadingLabel setTextColor:[UIColor colorWithRed:0.215 green:0.215 blue:0.215 alpha:1.0]];
[loadingLabel setFont:[UIFont fontWithName:#"Helvetica-Bold" size:14]];
reloadingSpinner = [[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(70, -25, 20, 20)];
[reloadingSpinner setActivityIndicatorViewStyle:UIActivityIndicatorViewStyleGray];
[reloadingSpinner startAnimating];
[reloadingSpinner setHidesWhenStopped:YES];
[feedList addSubview:reloadingSpinner];
[feedList addSubview:loadingLabel];
}
return cell;
}

Selected state of UIButton in UITableView

I have UIButton in each cell of UITableView. When I touch it, its state is set to selected. But when I scroll table view so the button isn't visible, the state is set to normal. How can I do it that UIButton remain selected?
Thank you.
Edit: Here is the cellForRowAtIndexPath code:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
}
cell.selectionStyle = UITableViewCellSelectionStyleNone;
if (indexPath.row < [messagesArray count]) {
Zprava *msgObj = [messagesArray objectAtIndex:indexPath.row];
int width = 0;
if ([[UIDevice currentDevice] orientation] == UIDeviceOrientationPortrait) {
width = 320;
} else {
width = 480;
}
CGSize boundingSize = CGSizeMake(width, CGFLOAT_MAX);
CGSize requiredSize = [msgObj.mmessage sizeWithFont:[UIFont systemFontOfSize:17] constrainedToSize:boundingSize lineBreakMode:UILineBreakModeWordWrap];
UIButton *background = [[UIButton alloc] initWithFrame:CGRectMake(10, 25, 300, requiredSize.height + 20)];
[background setBackgroundImage:[[UIImage imageNamed:#"balloon.png"] stretchableImageWithLeftCapWidth:15 topCapHeight:15] forState:UIControlStateNormal];
[background setBackgroundImage:[[UIImage imageNamed:#"selected-balloon.png"] stretchableImageWithLeftCapWidth:15 topCapHeight:15] forState:UIControlStateSelected];
[background addTarget:self action:#selector(action:) forControlEvents:UIControlEventTouchUpInside];
background.tag = msgObj.msgID;
[[cell contentView] addSubview:background];
[background release];
UILabel *dateLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 10, 285, 15)];
[dateLabel setFont:[UIFont systemFontOfSize:12]];
[dateLabel setLineBreakMode:UILineBreakModeWordWrap];
[dateLabel setTextColor:[UIColor lightGrayColor]];
[dateLabel setNumberOfLines:0];
[dateLabel setTextAlignment:UITextAlignmentRight];
[dateLabel setText:msgObj.mdate];
[dateLabel setBackgroundColor:[UIColor clearColor]];
[dateLabel setOpaque:NO];
[[cell contentView] addSubview:dateLabel];
[dateLabel release];
UILabel *messageLabel = [[UILabel alloc] initWithFrame:CGRectMake(20, 30, 275, requiredSize.height + 5)];
[messageLabel setFont:[UIFont systemFontOfSize:17]];
[messageLabel setLineBreakMode:UILineBreakModeWordWrap];
[messageLabel setTextColor:[UIColor blackColor]];
[messageLabel setNumberOfLines:0];
[messageLabel setText:msgObj.mmessage];
[messageLabel setBackgroundColor:[UIColor clearColor]];
[messageLabel setOpaque:NO];
[[cell contentView] addSubview:messageLabel];
[messageLabel release];
}
return cell;
}
Save button states somewhere in your model separately from table view and set buttons state in cellForRowAtIndexpath: method again.