i m new, i added this code to customize table view with image and button in row
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"ImageOnRightCell";
UILabel *mainLabel, *secondLabel;
UIImageView *photo;
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil)
{
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(100, 0.0, 100, 20)];
[button addTarget:self action:#selector(buttonPressedAction:) forControlEvents:UIControlEventTouchUpInside];
[button setTag:1];
[cell.contentView addSubview:button];
photo = [[UIImageView alloc] initWithFrame:CGRectMake(50.0, 0.0, 80.0, 45.0)];
photo.tag = PHOTO_TAG;
photo.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleHeight;
[cell.contentView addSubview:photo];
}
UIImage *theImage = [UIImage imageNamed:#"man.jpg"];
photo.image = theImage;
return cell;
}
image part coming in row of the table, but not the button .
what is the problem in it please
Try it....
UIButton *finalPriceBtn=[UIButton buttonWithType:UIButtonTypeCustom];
finalPriceBtn.tag=i+200;
finalPriceBtn.frame = CGRectMake(100, 0.0, 100, 20);
[finalPriceBtn addTarget:self action:#selector(goBtnClk:) forControlEvents:UIControlEventTouchUpInside];
finalPriceBtn.titleLabel.font=[UIFont systemFontOfSize:12];
[finalPriceBtn setTitle:[NSString stringWithFormat:#"$%.2f",tempVal] forState:UIControlStateNormal];
[finalPriceBtn setTitleColor:[UIColor colorWithRed: 2.0f/255.0f green: 155.0f/255.0f blue: 213.0f/255.0f alpha:1] forState:UIControlStateSelected];
[finalPriceBtn setTitleColor:[UIColor colorWithRed: 2.0f/255.0f green: 155.0f/255.0f blue: 213.0f/255.0f alpha:1] forState:UIControlStateNormal];
finalPriceBtn.titleLabel.textAlignment=UITextAlignmentLeft;
[cell.contentView addSubview:finalPriceBtn];
Hope i helped.
You are adding the button and then adding the image, therefore the image is on top of the button, do this:
[cell.contentView addSubview:photo];
Before this:
[cell.contentView addSubview:button];
You are adding image above your button so add it below the button.
Use your code like this :
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"ImageOnRightCell";
UILabel *mainLabel, *secondLabel;
UIImageView *photo;
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil)
{
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
photo = [[UIImageView alloc] initWithFrame:CGRectMake(50.0, 0.0, 80.0, 45.0)];
photo.tag = PHOTO_TAG;
photo.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleHeight;
[cell.contentView addSubview:photo];
UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
button.frame = CGRectMake(100, 0.0, 100, 20);
[button setBackgroundColor:[UIColor redColor]];// Here add some background color to check its visibility
[button addTarget:self action:#selector(buttonPressedAction:) forControlEvents:UIControlEventTouchUpInside];
[cell.contentView addSubview:button];
}
UIImage *theImage = [UIImage imageNamed:#"man.jpg"];
photo.image = theImage;
return cell;
}
Related
UITable view is working fine. when scrolling checked image is changed to uncheck. And also i need to take the particular checked image data in SAVE button Action.Can any body help me to solve this problem in prj.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:nil];
if(cell == nil)
{
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:nil];
cell.backgroundColor = [UIColor clearColor];
cell.selectionStyle= UITableViewCellSelectionStyleNone;
}
UIButton *btn = [[UIButton alloc]initWithFrame:CGRectMake(10,10, 20, 20)];
[btn setImage:[UIImage imageNamed:#"unchecked.png"] forState:UIControlStateNormal]; [cell addSubview:btn];
btn.tag=4;
forState:UIControlStateNormal];
[btn addTarget:self action:#selector(checkBoxClicked:) forControlEvents:UIControlEventTouchUpInside];
UILabel *lbl_name =[[UILabel alloc]initWithFrame:CGRectMake(35, 10, 100, 20)];
lbl_name.text=[NSString stringWithFormat:#"%#",[[arr1 valueForKey:#"Name"]objectAtIndex:indexPath.row]];
lbl_name.tag=5;
lbl_name.textColor=[UIColor blackColor];
[lbl_name setTextAlignment:NSTextAlignmentCenter];
lbl_name.font=[UIFont systemFontOfSize:15];
[cell addSubview:lbl_name];
return cell;
}
-(void)checkBoxClicked:(id)sender
{
UIButton *tappedButton = (UIButton*)sender;
if([tappedButton.currentImage isEqual:[UIImage imageNamed:#"unchecked.png"]])
{
[sender setImage:[UIImage imageNamed: #"checked.png"] forState:UIControlStateNormal];
} else {
[sender setImage:[UIImage imageNamed:#"unchecked.png"]forState:UIControlStateNormal];
}
}
Take one array which is Use to store IndexValue of Selected button,
#property (nonatomic,retain) NSMutableArray *arySelected;
Initialize array in ViewDidLoad,
- (void)viewDidLoad {
[super viewDidLoad];
self.arySelected = [[NSMutableArray alloc] init];
}
Change Code of TableViewCell Delegate,
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
if(cell == nil)
{
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:nil];
cell.backgroundColor = [UIColor clearColor];
cell.selectionStyle= UITableViewCellSelectionStyleNone;
}
UIButton *btn = [[UIButton alloc]initWithFrame:CGRectMake(10,10, 20, 20)];
if (![arySelected containsObject:[NSString stringWithFormat:#"%ld",(long)indexPath.row]])
{
[btn setImage:[UIImage imageNamed: #"checked.png"] forState:UIControlStateSelected];
}
else
{
[btn setImage:[UIImage imageNamed:#"unchecked.png"] forState:UIControlStateNormal];
}
btn.tag=indexPath.row;
[btn addTarget:self action:#selector(checkBoxClicked:) forControlEvents:UIControlEventTouchUpInside];
[cell addSubview:btn];
UILabel *lbl_name =[[UILabel alloc]initWithFrame:CGRectMake(35, 10, 100, 20)];
lbl_name.text=[NSString stringWithFormat:#"%#",[[arr1 valueForKey:#"Name"]objectAtIndex:indexPath.row]];
lbl_name.tag=5;
lbl_name.textColor=[UIColor blackColor];
[lbl_name setTextAlignment:NSTextAlignmentCenter];
lbl_name.font=[UIFont systemFontOfSize:15];
[cell addSubview:lbl_name];
return cell;
}
// On your button Event,
-(void)checkBoxClicked:(id)sender
{
sender.selected = ! sender.selected;
if (sender.selected)
{
[arySelected addObject:[NSString stringWithFormat:#"%ld",(long)sender.tag]];
}
else
{
[arySelected removeObject:[NSString stringWithFormat:#"%ld",(long)sender.tag]];
}
[self.tableView reloadData];
}
you use the deferent state to set image like this.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:nil];
if(cell == nil)
{
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:nil];
cell.backgroundColor = [UIColor clearColor];
cell.selectionStyle= UITableViewCellSelectionStyleNone;
}
UIButton *btn = [[UIButton alloc]initWithFrame:CGRectMake(10,10, 20, 20)];
[btn setImage:[UIImage imageNamed:#"unchecked.png"] forState:UIControlStateNormal];
[sender setImage:[UIImage imageNamed: #"checked.png"] forState:UIControlStateSelected];
btn.selected=NO;
btn.tag=4;
[btn addTarget:self action:#selector(checkBoxClicked:) forControlEvents:UIControlEventTouchUpInside];
[cell addSubview:btn];
UILabel *lbl_name =[[UILabel alloc]initWithFrame:CGRectMake(35, 10, 100, 20)];
lbl_name.text=[NSString stringWithFormat:#"%#",[[arr1 valueForKey:#"Name"]objectAtIndex:indexPath.row]];
lbl_name.tag=5;
lbl_name.textColor=[UIColor blackColor];
[lbl_name setTextAlignment:NSTextAlignmentCenter];
lbl_name.font=[UIFont systemFontOfSize:15];
[cell addSubview:lbl_name];
return cell;
}
-(void)checkBoxClicked:(id)sender
{
UIButton *tappedButton = (UIButton*)sender;
if (tappedButton.isSelected) {
tappedButton.selected=NO;
}
else
{
tappedButton.selected=YES;
}
}
I have trying this task since long time
(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] ;
}
long row = [indexPath row];
cell.textLabel.text = items[row];
cell.textLabel.textColor = [UIColor whiteColor];
cell.textLabel.highlightedTextColor = [UIColor blackColor];
cell.detailTextLabel.text = alertsTimeArray[row];
cell.textLabel.frame = CGRectMake(0, 0, 30, 10);
cell.detailTextLabel.textColor = [UIColor whiteColor];
cell.detailTextLabel.highlightedTextColor = [UIColor blackColor];
NSLog(#">> %#",alertsTypeArray);
if (![[alertsTypeArray objectAtIndex:indexPath.row] isEqualToString:#"Critical"]){
NSLog(#">> %#",alertsTypeArray);
UIButton * reset = [UIButton buttonWithType:UIButtonTypeCustom];
[reset addTarget:self
action:#selector(customActionPressedForAlertView:)
forControlEvents:UIControlEventTouchUpInside];
[reset setTitle:#"RESET" forState:UIControlStateNormal];
[reset setTitleColor:[UIColor colorWithRed:0/255.0 green:126/255.0 blue:255/255.0 alpha:1.0] forState:UIControlStateNormal];
reset.frame = CGRectMake(250.0f, 22.0f, 70.0f, 30.0f);
reset.tag = indexPath.row;
[cell addSubview:reset];
}
cell.backgroundColor = [UIColor clearColor];
return cell;
}
(void)customActionPressedForAlertView:(id)sender{
UIButton *mybutton = (UIButton *)sender;
[mybutton removeFromSuperview];
UIAlertView *resetAlert = [[UIAlertView alloc] initWithTitle:#"Are you sure to reset alert?" message:nil delegate:self cancelButtonTitle:#"Cancel" otherButtonTitles:#"Ok", nil];
[resetAlert show];
CGPoint buttonPosition = [sender convertPoint:CGPointZero toView:self.tableView];
NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:buttonPosition];
selectedIndex = indexPath.row;
}
But I'm not able to remove the RESET button from it super view cell Please help me.
Every time my alertsTypeArray will fill with two different alerts, "Critical" and "service". If it is service then I need to add reset button or else I shouldn't , if reset button added and the user clicks the resent button then the row should delete, so for the i deleted the one of the alertsTypeArray type , but the reset button is not removing from the tabel , if i load the table view , reset button come's to critical alert.
Thanks,
As rdelmar stated, you most likely are removing the button, but you are also probably adding on several buttons to the same cell (since you add without checking to see if it exists first).
Simply check if the button already exists and only add it to the cell if it doesn't.
Give your button an arbitrary tag (like 123) and check if that tag exists in the cell before adding it.
So change:
if (![[alertsTypeArray objectAtIndex:indexPath.row] isEqualToString:#"Critical"]){
NSLog(#">> %#",alertsTypeArray);
UIButton * reset = [UIButton buttonWithType:UIButtonTypeCustom];
[reset addTarget:self
action:#selector(customActionPressedForAlertView:)
forControlEvents:UIControlEventTouchUpInside];
[reset setTitle:#"RESET" forState:UIControlStateNormal];
[reset setTitleColor:[UIColor colorWithRed:0/255.0 green:126/255.0 blue:255/255.0 alpha:1.0] forState:UIControlStateNormal];
reset.frame = CGRectMake(250.0f, 22.0f, 70.0f, 30.0f);
reset.tag = indexPath.row;
[cell addSubview:reset];
}
To:
if (![[alertsTypeArray objectAtIndex:indexPath.row] isEqualToString:#"Critical"])
{
NSLog(#">> %#",alertsTypeArray);
UIButton *reset = (UIButton *)[cell.contentView viewWithTag:123];
if (reset == nil)
{
UIButton * reset = [UIButton buttonWithType:UIButtonTypeCustom];
[reset addTarget:self action:#selector(customActionPressedForAlertView:) forControlEvents:UIControlEventTouchUpInside];
[reset setTitle:#"RESET" forState:UIControlStateNormal];
[reset setTitleColor:[UIColor colorWithRed:0/255.0 green:126/255.0 blue:255/255.0 alpha:1.0] forState:UIControlStateNormal];
reset.frame = CGRectMake(250.0f, 22.0f, 70.0f, 30.0f);
reset.tag = 123;
[cell.contentView addSubview:reset];
}
Removing the button should be a bit simpler than you have it.
(void)customActionPressedForAlertView:(UIButton *)sender
{
UIButton *pressedButton = sender;
[pressedButton removeFromSuperview];
}
i am working with the tableview in which i added 2 buttons on one cell. Below is the code which i used
- (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];
}
cell.backgroundView =[[UIImageView alloc] initWithImage:[ [UIImage imageNamed:#"list-bg.png"] stretchableImageWithLeftCapWidth:0.0 topCapHeight:5.0] ];
tickbtn = [UIButton buttonWithType:UIButtonTypeCustom];
tickbtn.tag = 200+indexPath.row;
[tickbtn setBackgroundImage:[UIImage imageNamed:#"ok_gray.png"]forState:UIControlStateNormal];
[tickbtn addTarget:self action:#selector(addshed:) forControlEvents:UIControlEventTouchUpInside];
tickbtn.frame = CGRectMake(220, 10, 30, 30);
[cell.contentView addSubview:tickbtn];
NSLog(#"tickbtn tag %ld",(long)tickbtn.tag);
crossbtn = [UIButton buttonWithType:UIButtonTypeCustom];
crossbtn.tag = 400+indexPath.row;
[crossbtn setBackgroundImage:[UIImage imageNamed:#"delete-gray.png"]forState:UIControlStateNormal];
[crossbtn addTarget:self action:#selector(removeshed:) forControlEvents:UIControlEventTouchUpInside];
crossbtn.frame = CGRectMake(250, 10, 30, 30);
[cell.contentView addSubview:crossbtn];
NSLog(#"tickbtn tag %ld",(long)crossbtn.tag);
return cell;
}
on the tickbtn and crossbtn i am applying following actions :-
-(IBAction)addshed:(UIControl *)sender
{
NSIndexPath *indexPath = [NSIndexPath indexPathForRow:sender.tag-200 inSection:0];
UITableViewCell *cell = (UITableViewCell*)[list_table cellForRowAtIndexPath:indexPath];
UIButton *check1 = (UIButton*)[cell.contentView viewWithTag:indexPath.row+200];
UIButton *check2 = (UIButton*)[cell.contentView viewWithTag:indexPath.row+400];
UIImageView *btnimg1 = [[UIImageView alloc] initWithImage:check1.currentBackgroundImage];
//UIImageView *btnimg2 = [[UIImageView alloc] initWithImage:check2.currentBackgroundImage];
NSLog(#"SHED LIST subviews: %#", btnimg1.image);
// Shed_data *sheddata = [[Shed_data alloc] init];
if (btnimg1.image == [UIImage imageNamed:#"ok_gray.png"]) {
//btnimg.image = [UIImage imageNamed:#"ok_gray.png"];
[check1 setBackgroundImage:[UIImage imageNamed:#"ok_green.png"]forState:UIControlStateNormal];
[check2 setBackgroundImage:[UIImage imageNamed:#"delete-gray.png"]forState:UIControlStateNormal];
[self addsheddata:sender];
NSLog(#"tickbtn tag %ld",(long)tickbtn.tag);
}
else if (btnimg1.image == [UIImage imageNamed:#"ok_green.png"])
{
[check2 setBackgroundImage:[UIImage imageNamed:#"delete-red.png"]forState:UIControlStateNormal];
[check1 setBackgroundImage:[UIImage imageNamed:#"ok_gray.png"]forState:UIControlStateNormal];
[self removesheddata:sender];
}
}
-(IBAction)removeshed:(UIControl*)sender
{
//.…………………….. My functionality
}
but in both these cases i am getting the tag value of last cell only whenever i am pressing the buttons of the cell.
Please locate my error and help me out to solve it. Your help will be much appreciable.
Try this one as working fine for me. I Just tested with my Xcode 5.
Modification :
1. I Create an NSMutableArray with the name of _objects (_objects = [[NSMutableArray alloc]initWithObjects:#"one",#"two",#"thre", nil];). and give it to my UITableView.
2.Give the tickBtn and crossBtn an different color so easily visible.
3.change the button pressed function to UIControl to UIButton like -(IBAction)addshed:(UIButton *)sender and when button pressed i catch the tag value and print it out on the console.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"Cell" forIndexPath:indexPath];
cell.textLabel.text = [_objects objectAtIndex:indexPath.row];
cell.backgroundView =[[UIImageView alloc] initWithImage:[ [UIImage imageNamed:#"list-bg.png"] stretchableImageWithLeftCapWidth:0.0 topCapHeight:5.0] ];
tickbtn = [UIButton buttonWithType:UIButtonTypeCustom];
tickbtn.tag = 200+indexPath.row;
[tickbtn setBackgroundImage:[UIImage imageNamed:#"ok_gray.png"]forState:UIControlStateNormal];
[tickbtn setBackgroundColor:[UIColor blackColor]];
[tickbtn addTarget:self action:#selector(addshed:) forControlEvents:UIControlEventTouchUpInside];
tickbtn.frame = CGRectMake(220, 10, 30, 30);
[cell.contentView addSubview:tickbtn];
NSLog(#"tickbtn tag %ld",(long)tickbtn.tag);
crossbtn = [UIButton buttonWithType:UIButtonTypeCustom];
crossbtn.tag = 400+indexPath.row;
[crossbtn setBackgroundImage:[UIImage imageNamed:#"delete-gray.png"]forState:UIControlStateNormal];
[crossbtn addTarget:self action:#selector(removeshed:) forControlEvents:UIControlEventTouchUpInside];
crossbtn.frame = CGRectMake(250, 10, 30, 30);
[crossbtn setBackgroundColor:[UIColor greenColor]];
[cell.contentView addSubview:crossbtn];
NSLog(#"tickbtn tag %ld",(long)crossbtn.tag);
return cell;
}
-(IBAction)addshed:(UIButton *)sender {
NSLog(#"add shed %d",sender.tag);
}
-(IBAction)removeshed:(UIButton *)sender {
NSLog(#"remove %d",sender.tag);
}
NEW QUESTION UPDATE
Did you try with 10 or more cells and try with some continuous scroll?
And the result is
As the Another Answer says
[cell addSubview:crossbtn];// -------- Change here ---------
Let me clear this as i know about it.
The contentView is a subview of UITableViewCell. please review this reference and here you can see there are actually 3 subviews in a UITableViewCell.
You need to add your button to cell subview not cell's contentview subview. So use this 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];
}
cell.backgroundView =[[UIImageView alloc] initWithImage:[ [UIImage imageNamed:#"list-bg.png"] stretchableImageWithLeftCapWidth:0.0 topCapHeight:5.0] ];
tickbtn = [UIButton buttonWithType:UIButtonTypeCustom];
tickbtn.tag = 200+indexPath.row;
[tickbtn setBackgroundImage:[UIImage imageNamed:#"ok_gray.png"]forState:UIControlStateNormal];
[tickbtn addTarget:self action:#selector(addshed:) forControlEvents:UIControlEventTouchUpInside];
tickbtn.frame = CGRectMake(220, 10, 30, 30);
[cell addSubview:tickbtn];// -------- Change here ---------
NSLog(#"tickbtn tag %ld",(long)tickbtn.tag);
crossbtn = [UIButton buttonWithType:UIButtonTypeCustom];
crossbtn.tag = 400+indexPath.row;
[crossbtn setBackgroundImage:[UIImage imageNamed:#"delete-gray.png"]forState:UIControlStateNormal];
[crossbtn addTarget:self action:#selector(removeshed:) forControlEvents:UIControlEventTouchUpInside];
crossbtn.frame = CGRectMake(250, 10, 30, 30);
[cell addSubview:crossbtn];// -------- Change here ---------
NSLog(#"tickbtn tag %ld",(long)crossbtn.tag);
return cell;
}
Your code seems fine for cellForRowAtIndexpath:. Error might be in getting the tag value at button click. Try to change with this code:-
-(IBAction)addshed:(UIControl *)sender
{
//.…………………….. My functionality
int selectedRow1 = ((UIControl *)sender).tag;
NSLog(#"No. %d", selectedRow1);
}
I have seen issue. It may be lead to this type of error.
Why do you add subviews again and again to your cell's content view.?
That is, for every cellForRowAtIndexpath: call, button will be add to cell. In case dequeueReusableCellWithIdentifier:, your last cell may reuse to any other cell while scroll. It will lead to your error. that is your cell will contain two button.(tag with last cell and tag with your current cell).
In this line [cell.contentView addSubview:tickbtn];, you have to do some change according to add once and also for crossbtn.
Updation: I have seen your updated question. My suggestion, better use custom cell. Use this link to how to create custom cell.. Lot of confusion in your code. ex. in this line UITableViewCell *cell = (UITableViewCell*)[list_table cellForRowAtIndexPath:indexPath];, It will give unexpected. Don't call delegate method like this.
I'm a newbie. I am using this code to create a UITableViewCell but when I reload the table the button's image is not always correct, although all labels work fine. I don't know why. How can I fix this issue?
- (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];
UILabel *FileNameLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 0, 100, 30)];
FileNameLabel.tag = 1000;
FileNameLabel.backgroundColor = [UIColor clearColor];
FileNameLabel.font = [UIFont fontWithName:#"Helvetica" size:16];
FileNameLabel.font = [UIFont boldSystemFontOfSize:16];
FileNameLabel.textColor = [UIColor blackColor];
[cell.contentView addSubview: FileNameLabel];
[FileNameLabel release];
UILabel *UploadTimeLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 20, 150, 25)];
UploadTimeLabel.tag = 2000;
UploadTimeLabel.backgroundColor = [UIColor clearColor];
UploadTimeLabel.font = [UIFont fontWithName:#"Helvetica" size:12];
UploadTimeLabel.textColor = [UIColor grayColor];
[cell.contentView addSubview: UploadTimeLabel];
[UploadTimeLabel release];
UILabel *pricelabel = [[UILabel alloc] initWithFrame:CGRectMake(80, 0, 80, 30)];
pricelabel.backgroundColor = [UIColor clearColor];
pricelabel.font = [UIFont fontWithName:#"Helvetica" size:16];
pricelabel.font = [UIFont boldSystemFontOfSize:16];
pricelabel.textColor = [UIColor darkGrayColor];
pricelabel.tag = 3000;
//pricelabel.hidden = YES;
pricelabel.textAlignment = NSTextAlignmentRight;
[cell.contentView addSubview: pricelabel];
[pricelabel release];
market = [[UIButton alloc] init];;
[market setFrame:CGRectMake(200, 6, 30, 30)];
market.tag = 4000;
[market addTarget:self action:#selector(marketPressedAction:) forControlEvents:UIControlEventTouchDown];
[cell.contentView addSubview:market];
}
if( [temp count] > 0)
{
UILabel *fileNameLbl = (UILabel*)[cell.contentView viewWithTag:1000];
fileNameLbl.text =[temp objectAtIndex:indexPath.row];
UILabel *uploadlbl = (UILabel*)[cell.contentView viewWithTag:2000];
uploadlbl.text =[UploadTimeAllArr objectAtIndex:indexPath.row];
}
UIButton *marketButton = (UIButton*)[cell.contentView viewWithTag:4000];
[marketButton setTag:indexPath.row];
if([sellingArray count]>0)
{
NSLog(#"sellingArray %#",sellingArray);
if([[sellingArray objectAtIndex:indexPath.row] isEqualToString:#"0"]) // nothing
{
[marketButton setSelected:NO];
[marketButton setImage:[UIImage imageNamed:#"Marketplace.png"] forState:UIControlStateNormal];
marketButton.enabled = YES;
}
else if([[sellingArray objectAtIndex:indexPath.row] isEqualToString:#"2"]) // marketplace
{
[marketButton setSelected:YES];
[marketButton setImage:[UIImage imageNamed:#"MarketplaceSelect.png"] forState:UIControlStateNormal];
marketButton.enabled = YES;
}
}
return cell;
}
Your main problem here is that you are recreating new views in your cell every time this method is called. You want to create all reusable elements inside the if(cell == nil) otherwise it will make duplicates. Anything that is dynamic must be created outside of this. I took your code and modified it. This should work better.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
// Everything that does not change should go in here!
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier] autorelease];
UILabel *pricelabel = [[UILabel alloc] initWithFrame:CGRectMake(80, 0, 80, 30)];
pricelabel.backgroundColor = [UIColor clearColor];
pricelabel.font = [UIFont fontWithName:#"Helvetica" size:16];
pricelabel.font = [UIFont boldSystemFontOfSize:16];
pricelabel.textColor = [UIColor darkGrayColor];
pricelabel.tag = 3000;
//pricelabel.hidden = YES;
pricelabel.textAlignment = NSTextAlignmentRight;
[cell addSubview:pricelabel];
UIButton *market = [UIButton buttonWithType:UIButtonTypeCustom];
[market setFrame:CGRectMake(200, 6, 30, 30)];
[market addTarget:self action:#selector(marketPressedAction:) forControlEvents:UIControlEventTouchDown];
[cell addSubview:market];
}
// find market button, since we could be reusing a cell we cannot rely on a tag
// value to find it. (This would only work with one button though).
UIButton *market;
for (UIView *subview in cell.subviews) {
if ([subview isKindOfClass:[UIButton class]]) {
market = (UIButton *)subview;
break;
}
}
// set all defaults in case of reuse
[market setImage:[UIImage imageNamed:#"DefaultImage.png"] forState:UIControlStateNormal];
market.selected = YES;
market.enabled = NO;
market.clearsContextBeforeDrawing = NO;
if([sellingArray count] > 0) {
NSLog(#"sellingArray %#",sellingArray);
if([[sellingArray objectAtIndex:indexPath.row] isEqualToString:#"0"]) {
// not sure if this is supposed to be YES or NO
market.clearsContextBeforeDrawing = YES;
[market setSelected:NO];
[market setImage:[UIImage imageNamed:#"Marketplace.png"] forState:UIControlStateNormal];
market.enabled = YES;
}
}
[market setTag:indexPath.row];
return cell;
}
Since it appears you are not using ARC, make sure you look over this code for any needed reference counting.
dequeReusablecellWithIdentifier: method get return the cell instance already created available,If the reference points still to nil ,we need a valid cell and create one cell to return from that cellForRowatIndexpath: method.That is what being checked in the (cell ==nil).When you create a new cell it is creation and hence all settings custom and all has to be done here.
Second Edit:
This was copied from an answer above:
inside the -cellForRowAtIndexPath: method:
if (!cell) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellSubtitle];
UIButton *market = [UIButton buttonWithType:UIButtonTypeCustom];
[market setFrame:CGRectMake(200, 6, 30, 30)];
[market addTarget:self action:#selector(marketPressedAction:) forControlEvents:UIControlEventTouchDown];
[cell.contentView addSubview:market];
//Add all your UILabel INITIATION stuff here as well
}
UIButton *marketButton;
for (UIView *subview in cell.subviews) {
if ([subview isKindOfClass:[UIButton class]]) {
marketButton = (UIButton *)subview;
break;
}
}
marketButton.tag = [indexPath row];
UILabel *priceLabel = [cell.contentView viewWithTag:3000];
UILabel *uploadTimeLabel = [cell.contentView viewWithTag:2000];
//Set up your labels and button now
return cell;
}
EDIT: Leaving my original answer below for posterity but I see that you are setting the table index row as the MarketButton's tag. If you're using that to figure out which dataSource object to query, this is bad practice. You should be making a custom cell which can hold a reference to the object in your data source, so you don't have to ask the button for its tag, and then ask the data source array for the object at index:tag.
The reason this is bad is because somewhere, the state of your array could change, but the table cell is still displayed and still holds a tag pointing at the wrong index. If you just have the cell keep track of the object in question, no matter what happens to the array structure you're guaranteed to be modifying the object you need to.
The only thing I would change about Firo's answer is to just add a "tag" property to each view in the cell, so you don't have to iterate each time you want to find it.
Also took out the [[UIButton alloc]init] line because it's superfluous and might be considered a dangling pointer.
if (cell == nil) {
// Everything that does not change should go in here!
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier] autorelease];
UIButton *market = [UIButton buttonWithType:UIButtonTypeCustom];
[market setFrame:CGRectMake(200, 6, 30, 30)];
[market addTarget:self action:#selector(marketPressedAction:) forControlEvents:UIControlEventTouchDown];
market.tag = 9999;
[cell.contentView addSubview:market];
}
//don't have to do UIView iteration here
UIButton *marketButton = [cell.contentView viewWithTag:9999];
I have added 2 button in a row of table view, for all the rows, and these button clicked as it first time appear in table view , when I scroll the table list the button tapping disable,
here is my code
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"ImageOnRightCell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
cell.selectionStyle = UITableViewCellSelectionStyleGray;
cell.userInteractionEnabled = NO;
UIButton *finalPriceBtn=[UIButton buttonWithType:UIButtonTypeCustom];
UIButton *finalPriceBtn1=[UIButton buttonWithType:UIButtonTypeCustom];
if (cell == nil)
{
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
int i=indexPath.row;
finalPriceBtn.backgroundColor=[UIColor redColor];
finalPriceBtn.tag=MAINLABEL_TAG;
finalPriceBtn.frame = CGRectMake(200, 0.0, 100, 50);
[finalPriceBtn addTarget:self action:#selector(goBtnClk:) forControlEvents:UIControlEventTouchUpInside];
finalPriceBtn.titleLabel.font=[UIFont systemFontOfSize:12];
finalPriceBtn.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleHeight;
[finalPriceBtn setImage:[UIImage imageNamed:#"man.jpg"] forState:UIControlStateNormal ];
[cell.contentView addSubview:finalPriceBtn];
finalPriceBtn1.backgroundColor=[UIColor redColor];
finalPriceBtn1.tag=SECONDLABEL_TAG;
finalPriceBtn1.frame = CGRectMake(50.0, 0.0, 80.0, 45.0);
[finalPriceBtn1 addTarget:self action:#selector(goBtnClk:) forControlEvents:UIControlEventTouchUpInside];
finalPriceBtn1.titleLabel.font=[UIFont systemFontOfSize:12];
finalPriceBtn1.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleHeight;
[finalPriceBtn1 setImage:[UIImage imageNamed:#"bulk-female.jpg"] forState:UIControlStateNormal ];
[cell.contentView addSubview:finalPriceBtn1];
}
else
{
finalPriceBtn = (UIButton *)[cell.contentView viewWithTag:MAINLABEL_TAG];
finalPriceBtn1 = (UIButton *)[cell.contentView viewWithTag:SECONDLABEL_TAG];
}
return cell;
}
It is happening because, each time you are scrolling the tableview, your cells are reused and in that case cell is not nil and the code above the code before the cell==nil, makes the userInteractionEnabled to NO. That's why, your button is not clickable.
First time those buttons are clickable because they were not allocated, I mean the cell was not allocated and setting any attribute to non-allocated entity makes no effect. Hope you got the point.