TextFields are refreshed when table is scrolled - iphone

Please see the code
- (UITableViewCell *)tableView:(UITableView *)tableView
cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *SimpleTableIdentifier = #"SimpleTableIdentifier";
UITableViewCell *cell = [tableView
dequeueReusableCellWithIdentifier:SimpleTableIdentifier];
UILabel *playerHeading;
UITextField *txt;
if (cell == nil)
{
cell = [[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault
reuseIdentifier:SimpleTableIdentifier] autorelease];
playerHeading=[[UILabel alloc ]initWithFrame:CGRectMake(5.0f, 10.0f, 70.0f, 30.0f)];
txt=[[UITextField alloc]initWithFrame:CGRectMake(80.0f, 13.0f, 170.0f, 30.0f)];
txt.tag=2;
[txt setBackgroundColor:[UIColor clearColor]];
//[txt setTextColor:[UIColor blackColor]];
//[txt setBackgroundColor:[UIColor whiteColor]];
[txt setTextColor:[UIColor grayColor]];
txt.delegate=self;
//[txt setBorderStyle:UIBorderStyle ]
[txt setText:#"Enter Player name"];
//txt.layer.cornerRadius=8.0f;
// txt.layer.masksToBounds=YES;
//txt.layer.borderColor=[[UIColor redColor]CGColor];
// txt.layer.borderWidth= 1.0f;
[playerHeading setBackgroundColor:[UIColor clearColor]];
[playerHeading setFont:[UIFont boldSystemFontOfSize:15]];
[playerHeading setTag:1];
[playerHeading setBackgroundColor:[UIColor clearColor]];
NSString *str=[NSString stringWithFormat:#"Player %i",indexPath.row];
[playerHeading setText:str];
[playerHeading setFont:[UIFont boldSystemFontOfSize:15]];
// NSLog(#"row %i ,section %i",indexPath.row,indexPath.section);
[cell.contentView addSubview:playerHeading];
}
else
{
playerHeading = [cell.contentView viewWithTag:1];
txt=[cell.contentView viewWithTag:2];
// NSLog(#"row %i ,section %i",indexPath.row,indexPath.section);
}
if(indexPath.section%2==0){
playerHeading.textColor=[UIColor blueColor];
}
else{
playerHeading.textColor=[UIColor redColor];
}
playerHeading.text = [NSString stringWithFormat:#"Player %i",indexPath.row];
txt.tag=indexPath.section;
// NSString *nam=[NSString stringWithFormat:#"%i",indexPath.row];
// [txt setName:nam];
//txt.clearsOnBeginEditing=YES;
[cell.contentView addSubview:txt];
//cell.accessoryView=txt;
return cell;
}
I have created a UITable with 7 sections each section contains 4 players user need to fill the text fields in reach row , but issue is that when i scroll the table textfields become set to default value please help how can i set the textfields to fixed value inserted by used

For solving your problem is storing the user inserted string into a data structure which will give easy access to the string with the help of section and row.
You can use a NSMutableDictionary whose key will be section number which will store an array and the 'row' index of array will give you the string typed in that particular text field.
In cellForRowAtIndexPath you will have to check if string exists for that cell else show default string or placeholder.

Related

Display button click count in label for particular cell which are subviews to uitableview

I have a button and a label which are sub views to UITableView.
Initially label value is 0.
what i need is, when i click button on particular cell i want to increment value in same cell label (as 1) and display that value in same label.
And again i clicked same cell button the label in that cell should be increment (as 2) and display that value in same cell in UITableView.
My code..
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
UILabel *Lbl;
UIButton *btn;
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
Lbl =[[UILabel alloc]init];
[Lbl setFrame:CGRectMake(56, 60, 117, 12)];
[Lbl setBackgroundColor:[UIColor clearColor]];
[Lbl setTextAlignment:NSTextAlignmentLeft];
[Lbl setFont:[UIFont boldSystemFontOfSize:15.0]];
Lbl.tag=indexPath.row;
[cell.contentView addSubview:Lbl];
btn =[UIButton buttonWithType:UIButtonTypeCustom];
[btn setTitle:#"add" forState:UIControlStateNormal];
[btn setTitleColor:[UIColor colorWithRed:0.7 green:0 blue:0 alpha:1.0] forState:UIControlStateNormal];
[btn setTitleColor:[UIColor colorWithRed:0.7 green:0 blue:0 alpha:1.0] forState:UIControlStateHighlighted];
[[btn titleLabel] setFont:[UIFont boldSystemFontOfSize:23]];
[btn setFrame:CGRectMake(289, 2, 30, 71)];
btn.tintColor=[UIColor lightGrayColor];
btn.tag=indexPath.row;
[btn addTarget:self action:#selector(increaseItemCount:) forControlEvents:UIControlEventTouchUpInside];
[cell.contentView addSubview:btn];
} else {
Lbl =(UILabel *)[cell.contentView viewWithTag:indexPath.row];
btn =(UIButton *)[cell.contentView viewWithTag:indexPath.row];
}
cell.textLabel.text=#"title";
countLbl.text = [[NSString alloc] initWithFormat:#"%d",showItemCount];
return cell;
}
// button action method
-(void)increaseItemCount:(UIButton *)sender
{
UITableViewCell *cell = (UITableViewCell *)sender.superview.superview;
NSIndexPath *path = [tableView indexPathForCell:cell];
NSLog(#"row: %d",path.row);
UILabel *countLbl =(UILabel *)[cell.contentView viewWithTag:path.row];
showItemCount=[countLbl.text intValue] + 1;
NSLog(#"%d",showItemCount);
countLbl.text = [[NSString alloc] initWithFormat:#"%d",showItemCount];
}
I tried this, After clicking the value is showing in other cells and when i scroll the table view that value is showing in all cells.
Any suggestions or code
If you want source code, Download it from here https://github.com/MasudShuvo/TestCustomTableViewCell
I've modify the code as your requirement.
That's because it looks like you're using a single instance variable to store the itemCount. You should use an array to know which cell has been clicked how many times.
The code is however pretty messy, so you should write it again from scratch
indexPath.row begins 0 to n, we not set tag 0 for label and you use single variable showItemCount used to assign text in countLbl, table view reuse cell when it will appear,use array to store showItemCount for each cells
please do as per following:
#implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
selectedIndex=-1;
//[tblView reloadData];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return 2;
}
// Row display. Implementers should *always* try to reuse cells by setting each cell's reuseIdentifier and querying for available reusable cells with dequeueReusableCellWithIdentifier:
// Cell gets various attributes set automatically based on table (separators) and data source (accessory views, editing controls)
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
// UILabel *Lbl;
// UIButton *btn;
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
UILabel *Lbl =[[UILabel alloc]init];
[Lbl setFrame:CGRectMake(56, 60, 117, 12)];
[Lbl setBackgroundColor:[UIColor clearColor]];
[Lbl setTextAlignment:NSTextAlignmentLeft];
[Lbl setFont:[UIFont boldSystemFontOfSize:15.0]];
Lbl.tag=indexPath.row;
Lbl.text=[NSString stringWithFormat:#"%i",0];
[cell.contentView addSubview:Lbl];
UIButton *btn =[UIButton buttonWithType:UIButtonTypeCustom];
[btn setTitle:#"add" forState:UIControlStateNormal];
[btn setTitleColor:[UIColor colorWithRed:0.7 green:0 blue:0 alpha:1.0] forState:UIControlStateNormal];
[btn setTitleColor:[UIColor colorWithRed:0.7 green:0 blue:0 alpha:1.0] forState:UIControlStateHighlighted];
[[btn titleLabel] setFont:[UIFont boldSystemFontOfSize:23]];
[btn setFrame:CGRectMake(289, 2, 30, 71)];
btn.tintColor=[UIColor lightGrayColor];
btn.tag=indexPath.row;
[btn addTarget:self action:#selector(increaseItemCount:) forControlEvents:UIControlEventTouchUpInside];
[cell.contentView addSubview:btn];
NSLog(#"Selected Index:%i",indexPath.row);
} else {
UILabel *Lbl =(UILabel *)[cell.contentView viewWithTag:indexPath.row];
//UIButton *btn =(UIButton *)[cell viewWithTag:indexPath.row];
if(indexPath.row==selectedIndex)
{
NSLog(#"Selected Index in CellForRowAtIndexPath:%i",indexPath.row);
Lbl.text=[NSString stringWithFormat:#"%i",[Lbl.text intValue]+1];
}
}
// cell.textLabel.text=#"title";
//countLbl.text = [[NSString alloc] initWithFormat:#"%d",showItemCount];
return cell;
}
-(void)increaseItemCount:(UIButton *)sender
{
selectedIndex=sender.tag;
[tblView reloadData];
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
NSLog(#"Selected Index:%i",indexPath.row);
}
i hope this will help you.

Having trouble in displaying UITableView

Please see
- (UITableViewCell *)tableView:(UITableView *)tableView
cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *SimpleTableIdentifier = #"SimpleTableIdentifier";
UITableViewCell *cell = [tableView
dequeueReusableCellWithIdentifier:SimpleTableIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault
reuseIdentifier:SimpleTableIdentifier] autorelease];
UILabel *playerHeading=[[UILabel alloc ]initWithFrame:CGRectMake(5.0f, 10.0f, 70.0f, 30.0f)];
[playerHeading setBackgroundColor:[UIColor clearColor]];
NSString *str=[NSString stringWithFormat:#"Player %i",indexPath.row];
[playerHeading setText:str];
[playerHeading setFont:[UIFont boldSystemFontOfSize:15]];
if(indexPath.section%2==0){
playerHeading.textColor=[UIColor redColor];
}
else {
playerHeading.textColor=[UIColor blueColor];
}
UITextField *txt=[[UITextField alloc]initWithFrame:CGRectMake(80.0f, 13.0f, 170.0f, 30.0f)];
[txt setBackgroundColor:[UIColor clearColor]];
//[txt setBackgroundColor:[UIColor whiteColor]];
[txt setTextColor:[UIColor grayColor]];
txt.delegate=self;
//[txt setBorderStyle:UIBorderStyle ]
[txt setText:#"Enter Player name"];
//txt.layer.cornerRadius=8.0f;
// txt.layer.masksToBounds=YES;
//txt.layer.borderColor=[[UIColor redColor]CGColor];
// txt.layer.borderWidth= 1.0f;
[cell.contentView addSubview:txt];
[cell.contentView addSubview:playerHeading];
[cell.contentView setAlpha:0.8f];
//ce]ll.textLabel.text = [listData objectAtIndex:row];
}
return cell;
}
I want to display the number in sequence like Player 0, Player 1, Player 2...
but as I scroll the table i get numbers in random format like Player 1, Player 0 ,Player 3
Please help how to solve this issue.
You are adding the labels as new subviews all the time - this means you will have label above label above label, which is a waste of memory as well as a potential source of display issues.
When you create your cells (inside if (cell == nil) create and add the subviews at that point, and assign each one a tag. Then configure them all outside that loop. An example just with your playerHeading label:
UILabel *playerHeading;
if (cell == nil)
{
cell = [[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault
reuseIdentifier:SimpleTableIdentifier] autorelease];
playerHeading=[[UILabel alloc ]initWithFrame:CGRectMake(5.0f, 10.0f, 70.0f, 30.0f)];
[playerHeading setBackgroundColor:[UIColor clearColor]];
[playerHeading setFont:[UIFont boldSystemFontOfSize:15]];
[playerHeading setTag:1];
[cell.contentView addSubview:playerHeading];
}
else
{
playerHeading = [cell.contentView viewWithTag:1];
}
playerHeading.text = [NSString stringWithFormat:#"Player %i",indexPath.row];
You do appear to have more than one section in your table (you have an if statement on indexPath.section) so your player numbers will start again from 0 in each section with the above code.
try to close the {} of the if(cell == nil) earlier like here:
if (cell == nil) {
cell = [[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault
reuseIdentifier:SimpleTableIdentifier] autorelease];
}

How to insert a customized row below a row that is tapped

I am developing a project in which there is one requirement that in a table view when I tapped a row there should be one row added below that row and also I want that row to be customized as I want to add a text view in that row.
Please tell me how can I do this.
Any suggestions would be highly appreciated.
My current code:-
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell;
cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];`
if (cell == nil) {
cell = [self reuseTableViewCellWithIdentifier:CellIdentifier withIndexPath:indexPath];
}
UIImageView *imgViewBackground=(UIImageView *)[cell.contentView viewWithTag:20];
UIImageView *imgView=(UIImageView *)[cell.contentView viewWithTag:21];
UILabel *label1=(UILabel *)[cell.contentView viewWithTag:22];
UILabel *label2=(UILabel *)[cell.contentView viewWithTag:23];
UILabel *label3=(UILabel *)[cell.contentView viewWithTag:24];
[imgViewBackground setImage:[UIImage imageNamed:#"bba3.png"]
[imgView setImage:[UIImage imageNamed:#"picdefault.png"]];
[label1 setText:[self.usernameArray objectAtIndex:indexPath.row]];
[label2 setText:[NSString stringWithFormat:#"%#",[self.level1Array objectAtIndex:indexPath.row]]];
[label3 setText:[self.ageArray objectAtIndex:indexPath.row]]];
cell.selectionStyle = UITableViewCellSelectionStyleNone;//to remove blu selection color
return cell;
}
-(UITableViewCell *)reuseTableViewCellWithIdentifier:(NSString *)identifier withIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell =[[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier]autorelease];
if ([identifier isEqualToString:#"Cell"]) {
UIImageView *imageView=[[UIImageView alloc]initWithFrame:CGRectMake(10, 0, 300, 98)];
imageView.tag=20;
[imageView setImage:[UIImage imageNamed:#"bba2.png"]];
[cell.contentView addSubview:imageView];
[imageView release];
UIImageView *imagePicView=[[UIImageView alloc]initWithFrame:CGRectMake(25, 20, 60, 60)];
imagePicView.tag=21;
[cell.contentView addSubview:imagePicView];
[imagePicView release];
UILabel *namelabel=[[UILabel alloc]initWithFrame:CGRectMake(90, 20, 200, 20)];
namelabel.backgroundColor=[UIColor clearColor];
namelabel.font=[UIFont systemFontOfSize:15];
namelabel.tag=22;
[namelabel setTextAlignment:UITextAlignmentLeft];
[namelabel setTextColor:[UIColor blackColor]];
[cell.contentView addSubview:namelabel];
[namelabel release];
UILabel *activitylabel=[[UILabel alloc]initWithFrame:CGRectMake(90, 40, 200, 20)];
activitylabel.backgroundColor=[UIColor clearColor];
activitylabel.font=[UIFont italicSystemFontOfSize:14];
activitylabel.tag=23;
[activitylabel setTextAlignment:UITextAlignmentLeft];
[activitylabel setTextColor:[UIColor darkGrayColor]];
[cell.contentView addSubview:activitylabel];
[activitylabel release];
UILabel *agelabel=[[UILabel alloc]initWithFrame:CGRectMake(90, 60, 200, 20)];
agelabel.backgroundColor=[UIColor clearColor];
agelabel.font=[UIFont systemFontOfSize:13];
agelabel.tag=24;
[agelabel setTextAlignment:UITextAlignmentLeft];
[agelabel setTextColor:[UIColor darkGrayColor]];
[cell.contentView addSubview:agelabel];
[agelabel release];
}
return cell;
}
Look at the WWDC 2011 developer video for UITableView changes and tips - in there they describe how to do exactly that. Sadly there's not been any sample code I've ever been able to find, but they document the approach pretty well in the talk.

UITableView adding duplicate labels on top of each other

My UITableView is adding duplicate label on top of each other when I scroll up and down. So eventally so many labels get added that the add slows down and crash's.
- (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];
}
UILabel *label;
label = [[UILabel alloc] initWithFrame:nameFrame];
[label setText:[name objectAtIndex:indexPath.row + indexPath.section]];
[label setFont:[UIFont fontWithName:#"Helvetica" size:18]];
[label setBackgroundColor:[UIColor clearColor]];
[cell addSubview:label];
[label release];
label = [[UILabel alloc] initWithFrame:statusFrame];
[label setText:[status objectAtIndex:indexPath.row + indexPath.section]];
[label setFont:[UIFont fontWithName:#"Helvetica" size:18]];
[label setBackgroundColor:[UIColor clearColor]];
[label setTextAlignment:(UITextAlignmentRight)];
[cell addSubview:label];
[label release];
return cell;
}
You are dequeuing reusable cells so the UILabel already exists on each dequeued cell. Try the following code.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
UILabel *label;
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
label = [[UILabel alloc] initWithFrame:nameFrame];
label.tag = 1; //Important for finding this label
[label setText:[name objectAtIndex:indexPath.row + indexPath.section]];
[label setFont:[UIFont fontWithName:#"Helvetica" size:18]];
[label setBackgroundColor:[UIColor clearColor]];
[cell.contentView addSubview:label];
[label release];
label = [[UILabel alloc] initWithFrame:statusFrame];
label.tag = 2; //Important for finding this label
[label setText:[status objectAtIndex:indexPath.row + indexPath.section]];
[label setFont:[UIFont fontWithName:#"Helvetica" size:18]];
[label setBackgroundColor:[UIColor clearColor]];
[label setTextAlignment:(UITextAlignmentRight)];
[cell.contentView addSubview:label];
[label release];
}
else
{
label = (UILabel*)[cell.contentView viewWithTag:1];
label.text = [name objectAtIndex:indexPath.row + indexPath.section];
label = (UILabel*)[cell.contentView viewWithTag:2];
label.text = [status objectAtIndex:indexPath.row + indexPath.section];
}
return cell;
}
I did adjust the code to use the cell's contentView.
You need to simply remove the subview:
for (UIView * view in cell.contentView.subviews)
{
[view removeFromSuperview];
view = nil;
}
This will do the work "I had the same issue"
The way I solved this was not very elegant but worked.
The problem, as mentioned by Joe is that we are reusing the cells by dequeuing them. This means that sometimes we use a cell which already has its properties previously set, eg its textLabel. In my case it was due to differences in the cell structure. It was overlapping the imageview from one cell over another which shouldn't have an image at all.
I found that identifying the problematic parts and setting them to nil at the start of cellForRowAtIndex fixed the problem. This is the equivalent of wiping your cell slate clean before reusing it.
Here is an edited version of mine:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell * cell = [self.tableView dequeueReusableCellWithIdentifier:bCellIdentifier];
cell.imageView.image = Nil;
cell.textLabel.text = Nil;
_nameField.text = #"";
...
// Setting the code with regards to the cells here
...
return cell;
}
Hope this helps

iOS: UITableView reloadData not working

I have a UITableView with two sections: free and paid. Each section has a different kind of cell. The free cells have two labels and an image. The paid cells has two labels, an image and a button that allows the product to be bought. Once a product is bought, the BUY button on that particular cell must not be shown again. Said that, this is how the cells are initialized...
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *IDNormal = #"Normal";
static NSString *IDComplex = #"Complex";
if (indexPath.section == 0) { // show free objects
UITableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:IDNormal];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault
reuseIdentifier:IDNormal] autorelease];
// product description
UILabel * labelDescription = [[UILabel alloc] initWithFrame:CGRectMake(5.0, 54.0, 225, 18)];
[labelDescription setTextAlignment:UITextAlignmentLeft];
[labelDescription setBackgroundColor:[UIColor whiteColor ]];
[labelDescription setClipsToBounds:YES];
[labelDescription setFont:[UIFont systemFontOfSize:14.0]];
[labelDescription setTextColor:[UIColor blackColor]];
[labelDescription setAlpha:0.6];
[labelDescription setTag: 860];
[cell addSubview:labelDescription];
[labelDescription release];
// this will show the word FREE on free objects (cells)
UILabel * labelFREE = [[UILabel alloc] initWithFrame:CGRectMake(235.0, 54.0, 80, 18)];
[labelFREE setTextAlignment:UITextAlignmentCenter];
[labelFREE setBackgroundColor:[UIColor greenColor ]];
[labelFREE setClipsToBounds:YES];
[labelFREE setFont:[UIFont boldSystemFontOfSize:14.0]];
[labelFREE setTextColor:[UIColor blackColor]];
[labelFREE setAlpha:0.75];
[labelFREE setText:NSLocalizedString(#"freeKey", #"")];
[labelFREE setTag: 861];
[cell addSubview:labelFREE];
[labelFREE release];
}
cell.imageView.image = [UIImage imageWithContentsOfFile:[[NSBundle mainBundle]
pathForResource:[NSString stringWithFormat: #"free%d", indexPath.row] ofType:#"jpg"]];
NSString * prefixLabel = [NSString stringWithFormat: #"gratis%d", indexPath.row];
UILabel *labelDescription2 = (UILabel*)[cell viewWithTag:860];
[labelDescription2 setText:#"FREE"];
return cell;
} else { // show paid objects
UITableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:IDComplex];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault
reuseIdentifier:IDComplex] autorelease];
UILabel * labelDescription = [[UILabel alloc] initWithFrame:CGRectMake(5.0, 54.0, 225, 18)];
[labelDescription setTextAlignment:UITextAlignmentLeft];
[labelDescription setBackgroundColor:[UIColor whiteColor ]];
[labelDescription setClipsToBounds:YES];
[labelDescription setFont:[UIFont systemFontOfSize:14.0]];
[labelDescription setTextColor:[UIColor blackColor]];
[labelDescription setAlpha:0.6];
[labelDescription setTag: 1];
[cell addSubview:labelDescription];
[labelDescription release];
}
int numberPaidObject = indexPath.row + 500;
cell.imageView.image = [UIImage imageWithContentsOfFile:[[NSBundle mainBundle]
pathForResource:[NSString stringWithFormat: #"table-pg%d", numberPaidObject] ofType:#"jpg"]];
NSString * nomeDoProduto = [NSString stringWithFormat: #"paid%d", numberPaidObject];
if ( NotSoldProduct ) {
NSString * prefixoEtiqueta = [NSString stringWithFormat: #"paid%d", numberPaidObject];
UILabel *labelDescription2 = (UILabel*)[cell viewWithTag:1];
[labelDescription2 setText:[description objectAtIndex: numberPaidObject ];
}
return cell;
}
}
as I have to identify which BUY button was clicked and I am using dequeueReusableCellWithIdentifier, so I have to use the following method...
- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
int numeroOfPaidObject = indexPath.row + 500;
if ((indexPath.section == 1) && ObjectForSale) {
// if paid objects and object was not bought yet
// in theory this section will not be executed if the object was already bought and paid
// so, I am skipping the BUY button creation and, in theory the cell will not have a BUY
// button… the problem is that it does...
UIButton * buyButton = [[UIButton alloc] initWithFrame:CGRectMake( 235, 45, 80, 30)];
buyButton.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
buyButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentCenter;
[buyButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
buyButton.titleLabel.font = [UIFont boldSystemFontOfSize:14];
buyButton.backgroundColor = [UIColor clearColor];
[buyButton addTarget:self action:#selector(buyNow:) forControlEvents:UIControlEventTouchDown];
[buyButton setTitle:NSLocalizedString(#"buyKey", #"") forState:UIControlStateNormal];
UIImage *newImage = [[UIImage imageWithContentsOfFile:[[NSBundle mainBundle]
pathForResource: #"whiteButton" ofType:#"png"]]
stretchableImageWithLeftCapWidth:12.0f topCapHeight:0.0f];
[buyButton setBackgroundImage:newImage forState:UIControlStateNormal];
[buyButton setTag: numeroOfPaidObject];
[cell addSubview:buyButton];
[buyButton release];
}
}
The problem with this code is: when I reload table's data the BUY button continues to show up on all cells, including those that was already bought by the user.
Any ideas?
thanks for any help.
You can step through it with the debugger, but here is my guess:
Because table cells are being reused, eventually all of the already purchased items end up in table cells that were previously occupied by an unpurchased item and therefore have had a buy button added to them.
If this is the case you need to add an else clause in your second section of code that deletes the button from the cell if the product has already been purchased.
Another problem is that your code is adding a new button every time a cell is displayed, so many/most of your cells probably have several buttons in them.
You will want to refactor your code so that the button is added once, in tableView:cellForRowAtIndexPath:, and only for newly-created cells.
There are two ways to do that:
Split the "Complex" cell type into two types: purchased and unpurchased, and create/dequeue them separately. Add the button only to to the unpurchased cell type.
Add the buttons to all of the cells in the "paid" section, and hide it when the item has been purchased.
In either case you'll need a way to grab a pointer to the button. The preferred way to do this is with the tag property, making it a one liner:
UIButton * button = [cell viewForTag:42];
...
You can also iterate through the subviews of the cell looking for UIButton objects:
UIButton *button = nil;
foreach (UIView *view in cell.subviews) {
if ([view isKindOfClass:[UIButton class]])
button = (UIButton *)view;
}
I would suggest using a constant tag to identify the button, and then rewrite your buyNow: method as follows:
-(IBAction)buyNow:(id)sender {
UITableViewCell *cell = (UITableViewCell *)((UIView *)sender).superview;
int itemID = [tableView indexPathForCell:cell].row + 500;
...
}
Perhaps I am thinking too simply here but a table view will function just fine with only the delegates set, but will fail to respond to reloadData if you have not made the connection in IB, did you check that?