how to add more than one image and button in UITableView? - iphone

I want to add more than one image in table view.
I can add one image using cell.imageview.image.
but how to add one more image.
And I also want to add buttons in all cells.
How can I do that ?

You should make your own UITableViewCell subclass. There are many tutorials for that:
http://iphone.zcentric.com/2008/08/05/custom-uitableviewcell/
http://www.icodeblog.com/2009/05/24/custom-uitableviewcell-using-interface-builder/
http://www.e-string.com/content/custom-uitableviewcells-interface-builder
Including:
http://stackoverflow.com
http://www.google.com

Make your own UITableViewCell subclass.

Use a UITableView with a custom cell with whatever you want in it, load extra images and labels. To get the custom cell, create an IBOutlet to the cell and use this method.
[[NSBundle mainBundle] loadNibNamed:#"customCellView" owner:self options:nil];
To make a cell, make a new Nib/Xib file which is blank, make files owner the class with the cells, drag a UITableviewcell object out and put whatever objects you want on top of that view, set background as clear color and when you load the nib, enter all info into those images and labels. GL

Here is a block of code I use alot in my apps. Its not the fastest way to implement, but it gives you complete control over how the cell looks and whats in it. Using the code below you can see how my app looks. You have 2 buttons on one cell. They both do something different when pushed, and if the actual CELL is selected I do something else. I removed some of the code because im sure you dont care about what Im doing when the cell is selected, only how to get the buttons on, and know which one is pushed.
-(void)scheduleServiceButtonPressed:(id)sender {
//when the user click the button "service appt" on a table cell, we get the cellRow and use that to identify which car to show
ServiceApptViewController * vc = (ServiceApptViewController *)[[ServiceApptViewController alloc] init];
vc.cameFromGarageSelectionInt = [sender tag]; // here is the cell row that was selected.
[self.navigationController pushViewController:vc animated:YES];
[vc release];
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
return 70;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [app.savedUserVehicleArray count];
}
// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:CellIdentifier] autorelease];
[cell setAccessoryType:UITableViewCellAccessoryDisclosureIndicator];
}
cell = [self getCellContentView:CellIdentifier:indexPath.row];
[cell setBackgroundColor:[UIColor redColor]];
cell.selectionStyle = UITableViewCellSelectionStyleNone;
NSLog(#"out cells for index");
return cell;
}
- (UITableViewCell *) getCellContentView:(NSString *)cellIdentifier:(int)cellIndex {
NSLog(#"in content");
vehicleForRow = [app.savedUserVehicleArray objectAtIndex:cellIndex];
//CGRect CellFrame = CGRectMake(0, 0, 300, 60);
CGRect CellFrame = CGRectMake(0, 0, 320, 70);
UITableViewCell *cell = [[[UITableViewCell alloc] initWithFrame:CellFrame reuseIdentifier:cellIdentifier] autorelease];
// put a UIView underneath for coloring
UIView * view = [[UIView alloc] initWithFrame:CellFrame];
if ( cellIndex%2 == 0 ){
view.backgroundColor = [UIColor whiteColor];
}else{
//view.backgroundColor = [UIColor colorWithRed:0.98 green:0.92 blue:0.52 alpha:1.0];
view.backgroundColor = [UIColor colorWithRed:.238 green:.238 blue:0.238 alpha:.10];
}
[cell.contentView addSubview:view];
[view release];
if (vehicleForRow.isDefault && [vehicleForRow.isDefault compare:#"YES"]==0) {
//add green check mark if vehicle is default
UIImageView * bgimage3 = [[UIImageView alloc] initWithFrame:CGRectMake(245, 15, 40, 32)];
bgimage3.image = [UIImage imageNamed:#"greenCheckMark.png"];
[cell.contentView addSubview:bgimage3];
[bgimage3 release];
//default vehicle label
UILabel *lblTemp;
NSString * z = [NSString stringWithFormat:#"Default"];
NSString * s1 = z;
CGRect Label1Frame = CGRectMake(240, 43, 250, 25); // name
lblTemp = [[UILabel alloc] initWithFrame:Label1Frame];
lblTemp.adjustsFontSizeToFitWidth = TRUE;
lblTemp.text = s1;
lblTemp.font = [UIFont boldSystemFontOfSize:12];
lblTemp.textColor = [UIColor blueColor];
lblTemp.backgroundColor = [UIColor clearColor];
[lblTemp setTextAlignment:UITextAlignmentLeft];
[cell.contentView addSubview:lblTemp];
}
else {
UIImageView * bgimage3 = [[UIImageView alloc] initWithFrame:CGRectMake(250, 15, 30, 24)];
bgimage3.image = [UIImage imageNamed:#"grayCheckMark.png"];
[cell.contentView addSubview:bgimage3];
[bgimage3 release];
UILabel *lblTemp;
NSString * z = [NSString stringWithFormat:#"Set As Default"];
NSString * s1 = z;
CGRect Label1Frame = CGRectMake(233, 38, 250, 25); // name
lblTemp = [[UILabel alloc] initWithFrame:Label1Frame];
lblTemp.adjustsFontSizeToFitWidth = TRUE;
lblTemp.text = s1;
lblTemp.font = [UIFont boldSystemFontOfSize:8];
lblTemp.textColor = [UIColor grayColor];
lblTemp.backgroundColor = [UIColor clearColor];
[lblTemp setTextAlignment:UITextAlignmentLeft];
[cell.contentView addSubview:lblTemp];
}
// add service button to each cell
UIImage *image;
schedServiceButton = [UIButton buttonWithType:UIButtonTypeCustom];
image = [UIImage imageNamed:#"tableServiceButton.png"];
[schedServiceButton setBackgroundImage:image forState:UIControlStateNormal];
schedServiceButton.frame = CGRectMake(5, 30, 97, 35);
[schedServiceButton setTag:cellIndex];//this is how we know which cell button was pressed
[schedServiceButton addTarget:self action:#selector(scheduleServiceButtonPressed:) forControlEvents:UIControlEventTouchUpInside];
schedServiceButton.titleLabel.font = [UIFont systemFontOfSize:12];
[schedServiceButton.titleLabel setLineBreakMode:UILineBreakModeCharacterWrap];
[schedServiceButton setTitle:#"Schedule\nService Appt." forState:UIControlStateNormal];
schedServiceButton.titleLabel.textAlignment = UITextAlignmentCenter;
[cell.contentView addSubview:schedServiceButton];
//yes add owners manual button
viewOMButton = [UIButton buttonWithType:UIButtonTypeCustom];
image = [UIImage imageNamed:#"tableOMButton.png"];
[viewOMButton setBackgroundImage:image forState:UIControlStateNormal];
viewOMButton.frame = CGRectMake(105, 30, 97, 35);
[viewOMButton setTag:cellIndex];
[viewOMButton addTarget:self action:#selector(viewOwnersManualButtonPressed:) forControlEvents:UIControlEventTouchUpInside];
viewOMButton.titleLabel.font = [UIFont systemFontOfSize:12];
[viewOMButton.titleLabel setLineBreakMode:UILineBreakModeCharacterWrap];
[viewOMButton setTitle:#"View\nOwner's Manual" forState:UIControlStateNormal];
viewOMButton.titleLabel.textAlignment = UITextAlignmentCenter;
[cell.contentView addSubview:viewOMButton];
//car description label
UILabel *lblTemp;
NSString * z = [NSString stringWithFormat:#"%# %# %#",vehicleForRow.userVehicleYear,vehicleForRow.userVehicleMake,vehicleForRow.userVehicleModel];
NSString * s1 = z;
CGRect Label1Frame = CGRectMake(10, 5, 250, 25); // name
//Initialize Label with tag 1.
lblTemp = [[UILabel alloc] initWithFrame:Label1Frame];
lblTemp.adjustsFontSizeToFitWidth = TRUE;
lblTemp.text = s1;
lblTemp.font = [UIFont boldSystemFontOfSize:16];
lblTemp.textColor = [UIColor blueColor];
lblTemp.backgroundColor = [UIColor clearColor];
[lblTemp setTextAlignment:UITextAlignmentLeft];
[cell.contentView addSubview:lblTemp];
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
}
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
}

Related

UITableView header for section only appears when scrolling down

I have some weird behavior on the iPad that I am not getting on the iPhone.
I have a Grouped table view that has sections and headers for the sections, the problem is that on the iPad the top most section's header is not displayed, when scrolling down the table the sections header appears for a short while just before going of screen.
Before scrolling
http://desmond.imageshack.us/Himg525/scaled.php?server=525&filename=screenshot2012051410074.png&res=landing http://desmond.imageshack.us/Himg525/scaled.php?server=525&filename=screenshot2012051410074.png&res=landing
After scrolling
http://desmond.imageshack.us/Himg59/scaled.php?server=59&filename=screenshot2012051410074.png&res=landing http://desmond.imageshack.us/Himg59/scaled.php?server=59&filename=screenshot2012051410074.png&res=landing
The code for creating the headers of the sections:
- (UIView *) tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
NSString *sectionTitle = [self tableView:tableView titleForHeaderInSection:section];
if (sectionTitle == nil || [sectionTitle isEqualToString:#""]) {
return nil;
}
// Create label with section title
UILabel *label = [[UILabel alloc] init] ;
label.frame = CGRectMake(12, 0, 300, 30);
label.backgroundColor = [UIColor clearColor];
label.textColor = [UIColor blackColor];
label.shadowColor = [UIColor whiteColor];
label.shadowOffset = CGSizeMake(0.0, 1.0);
label.font = [UIFont boldSystemFontOfSize:16];
label.text = sectionTitle;
UIImage *img = [UIImage imageNamed:#"header"];
UIImageView *imgView = [[UIImageView alloc] initWithFrame:CGRectMake(10, 0, 300, 44)];
imgView.image = img;
UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, tableView.bounds.size.width, 44)];
[view addSubview:imgView];
[view addSubview:label];
return view;
}
-(NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
int aSection = [[self.sectionsToDisplay objectAtIndex:section] integerValue];
return [self.groupHeadings objectAtIndex:aSection];
}
My TableView's code:
tableViewResult = [[UITableView alloc] initWithFrame:mainView.frame style:UITableViewStyleGrouped];
tableViewResult.separatorColor = [UIColor clearColor];
[mainView addSubview:tableViewResult];
I set the delegate and datasource in another method as I first do a web request before loading any data into the table, ie when the web request is done I do:
tableViewResult.delegate = self;
tableViewResult.dataSource = self;
[tableViewResult reloadData];
Everything works as expected except for the header of the top most section, and only on the iPad.
Any ideas what can cause this behavior?
What fixed the issue was changing this function to:
-(NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
int aSection = [[self.sectionsToDisplay objectAtIndex:section] integerValue];
if([[self.groupHeadings objectAtIndex:aSection] isEqualToString:#""])
return nil;
return [self.groupHeadings objectAtIndex:aSection];
}

UIButton with UIImages in a UITableViewCell - Overlapping etc

I have a problem with my UITableViewCell's. I am developing an application where certain posts in a feed may contain an image, and the button clicked will also need to contain a 'tag' number depending on which row of the table it is as I have an array of images downloaded.
The problem lies when I am scrolling (as you have already guessed) the table. The image loads fine, however when I scroll up/down the image will then go above other cells, and when the cell is shown back on the screen, the image will quickly change it's position to the proper position etc.
Here's the code for my UITableView:
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [feed count];
}
- (UITableViewCell *) getCellContentView:(NSString *)cellIdentifier
{
CGRect rect = [self.tableView bounds];
CGRect CellFrame = CGRectMake(0.0f, 0.0f, rect.size.width, 10.0f);
CGRect TitleFrame = CGRectMake(55.0f, 10.0f, 240.0f, 15.0f);
CGRect TextFrame = CGRectMake(55.0f, 25.0f, 250.0f, 15.0f);
CGRect PinFrame = CGRectMake(21.0f, 10.0f, 30.0f, 30.0f);
CGRect ViewFrame = CGRectMake(50.0f, 35.0f, 260.0f, 0.0f);
CGRect CommentsFrame = CGRectMake(300.0f, 10.0f, 20.0f, 15.0f);
UILabel * lblTemp;
UITableViewCell * cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
[cell setFrame:CellFrame];
lblTemp = [[UILabel alloc] initWithFrame:TitleFrame];
lblTemp.tag = 1;
lblTemp.numberOfLines = 0;
lblTemp.opaque = NO;
lblTemp.font = [UIFont systemFontOfSize:13.0f];
lblTemp.backgroundColor = [UIColor clearColor];
lblTemp.textColor = [UIColor blackColor];
lblTemp.textAlignment = UITextAlignmentLeft;
lblTemp.shadowColor = [UIColor whiteColor];
lblTemp.shadowOffset = CGSizeMake(0, 1);
[cell.contentView addSubview:lblTemp];
lblTemp = [[UILabel alloc] initWithFrame:TextFrame];
lblTemp.tag = 2;
lblTemp.numberOfLines = 0;
lblTemp.lineBreakMode = UILineBreakModeWordWrap;
lblTemp.adjustsFontSizeToFitWidth = NO;
lblTemp.font = [UIFont systemFontOfSize:13.0f];
lblTemp.textColor = [UIColor lightGrayColor];
lblTemp.backgroundColor = [UIColor clearColor];
lblTemp.shadowColor = [UIColor whiteColor];
lblTemp.shadowOffset = CGSizeMake(0, 1);
[cell.contentView addSubview:lblTemp];
lblTemp = [[UILabel alloc] initWithFrame:CommentsFrame];
lblTemp.tag = 5;
lblTemp.numberOfLines = 1;
lblTemp.font = [UIFont systemFontOfSize:13.0f];
lblTemp.textColor = [UIColor lightGrayColor];
lblTemp.backgroundColor = [UIColor whiteColor];
lblTemp.shadowColor = [UIColor whiteColor];
lblTemp.shadowOffset = CGSizeMake(0, 1);
[cell.contentView addSubview:lblTemp];
UIImageView * imgTemp = [[UIImageView alloc] initWithFrame:PinFrame];
imgTemp.tag = 3;
[cell.contentView addSubview:imgTemp];
UIView * viewTemp = [[UIView alloc] initWithFrame:ViewFrame];
viewTemp.tag = 4;
[viewTemp setBackgroundColor:[UIColor whiteColor]];
[cell.contentView addSubview:viewTemp];
return cell;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString * CellIdentifier = #"Cell";
UITableViewCell * cell = [self.tableView dequeueReusableCellWithIdentifier:CellIdentifier];
//UITableViewCell * cell = [self getCellContentView:CellIdentifier];
if (cell == nil) {
cell = [self getCellContentView:CellIdentifier];
} else {
[cell.contentView viewWithTag:999];
}
cell.backgroundColor = [UIColor clearColor];
UILabel * title = (UILabel *)[cell viewWithTag:1];
UILabel * journey = (UILabel *)[cell viewWithTag:2];
UIImageView * pin = (UIImageView *) [cell viewWithTag:3];
UILabel * comments = (UILabel *)[cell viewWithTag:5];
title.text = [NSString stringWithFormat:#"%#", [[feed objectAtIndex:indexPath.row] objectForKey:#"comment"]];
[title sizeToFit];
title.frame = CGRectMake(title.frame.origin.x, title.frame.origin.y, 240, title.frame.size.height);
if ([[feed objectAtIndex:indexPath.row] objectForKey:#"weather_desc"] != [NSNull null] ||
[[feed objectAtIndex:indexPath.row] objectForKey:#"weather_temp"] != [NSNull null]) {
journey.text = [NSString stringWithFormat:#"It's %# and %#°C.", [[feed objectAtIndex:indexPath.row] objectForKey:#"weather_desc"], [[feed objectAtIndex:indexPath.row] objectForKey:#"weather_temp"]];
} else {
journey.text = [NSString stringWithFormat:#"%#", [[[feed objectAtIndex:indexPath.row] objectForKey:#"journey"] objectForKey:#"name"]];
}
journey.frame = CGRectMake(journey.frame.origin.x, 10 + title.frame.size.height, 240, 15);
if ([[feed objectAtIndex:indexPath.row] objectForKey:#"latitude"] != [NSNull null]) {
pin.image = [UIImage imageNamed:#"LocationPin.png"];
} else {
pin.image = [UIImage imageNamed:#"Pin.png"];
}
if ([[feed objectAtIndex:indexPath.row] objectForKey:#"image_file_size"] != [NSNull null]) {
NSString * text = [NSString stringWithFormat:#"%#", [[feed objectAtIndex:indexPath.row] objectForKey:#"comment"]];
CGFloat height = [text sizeWithFont:[UIFont systemFontOfSize:13] constrainedToSize:CGSizeMake(250, 1500) lineBreakMode:UILineBreakModeWordWrap].height;
UIImage * myImage = [images objectForKey:[NSString stringWithFormat:#"%i", indexPath.row]];
UIButton * button = [[UIButton alloc] initWithFrame:CGRectZero];
[button setBackgroundImage:myImage forState:UIControlStateNormal];
[button setFrame:CGRectMake(title.frame.origin.x + 55.0f, 40.0f + height, 250.0f, myImage.size.height)];
[button setTag:10 + indexPath.row];
[button addTarget:self action:#selector(imagePressed:) forControlEvents:UIControlEventTouchUpInside];
[cell addSubview:button];
UIView * backView = (UIView *) [cell viewWithTag:4];
[backView setFrame:CGRectMake(title.frame.origin.x + 50.0f, 35.0f + height, 260.0f, myImage.size.height + 10.0f)];
} else {
UIView * backView = (UIView *) [cell viewWithTag:4];
[backView setFrame:CGRectZero];
[backView setBackgroundColor:[UIColor clearColor]];
}
comments.text = [NSString stringWithFormat:#"%i", [[[feed objectAtIndex:indexPath.row] objectForKey:#"comments"] count]];
UIImage * background = [UIImage imageNamed:#"CellBackground.png"];
UIImageView *imageView = [[UIImageView alloc] initWithImage:background];
imageView.contentMode = UIViewContentModeScaleToFill;
[cell setBackgroundView:imageView];
return cell;
}
- (void)tableView:(UITableView *)tv didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
[self.tableView deselectRowAtIndexPath:indexPath animated:NO];
MilestoneView * milestoneView = [[MilestoneView alloc] initWithNibName:#"MilestoneView" bundle:nil];
[milestoneView setMilestone:[feed objectAtIndex:indexPath.row]];
[self.navigationController pushViewController:milestoneView animated:YES];
}
- (CGFloat)tableView:(UITableView *)tv heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSString * text = [NSString stringWithFormat:#"%#", [[feed objectAtIndex:indexPath.row] objectForKey:#"comment"]];
CGFloat height = [text sizeWithFont:[UIFont systemFontOfSize:13] constrainedToSize:CGSizeMake(240, 1500) lineBreakMode:UILineBreakModeWordWrap].height;
if ([[feed objectAtIndex:indexPath.row] objectForKey:#"image_file_size"] != [NSNull null]) {
UIImage * myImage = [images objectForKey:[NSString stringWithFormat:#"%i", indexPath.row]];
height += myImage.size.height + 15.0f;
}
return height + 37;
}
I am also using Apple's inbuilt 'ARC' with iOS 5.0.
Kind regards,
Dominic
In this code you add button in cellForRowAtIndexPath , hence this is happen....
so , you add the code for button , backView in getCellContentView and fetch images from array in getCellContentView.
UIImage *myImage = [images objectForKey:[NSString stringWithFormat:#"%i", indexPath.row]];
then,
UIButton *button = [[UIButton alloc] initWithFrame:CGRectZero];
[button setBackgroundImage:myImage forState:UIControlStateNormal];
[button setFrame:CGRectMake(55.0f, 40.0f, 250.0f, myImage.size.height)];
change height , width & x,y co-or. what u want and
set cell index to button.
[button setTag:indexPath.row];
[button addTarget:self action:#selector(imagePressed:) forControlEvents:UIControlEventTouchUpInside];
[cell.contentView addSubview:button];
Let me know if you have any problem....
Replace following function header
- (UITableViewCell *) getCellContentView:(NSString *)cellIdentifier {
.
.
}
with this function
- (UITableViewCell *) getCellContentView:(NSString *)cellIdentifier indexPathForButtonTag:(NSIndexPath*)indexPath {
.
.
}
Replace following line in cellForRowAtIndex
cell = [self getCellContentView:CellIdentifier];
With the
cell = [self getCellContentView:CellIdentifier indexPathForButtonTag:indexPath];
You dont need each button to have a different tag. You should not be adding any subviews to the cell in cellForRowAtIndexPath because you will inevitably end up adding subview on top of subview. I notice you are also adding an image view as the cell's background in this method - you should only do this when you are creating a new cell.
Im going to assume there is a good reason you are not using a xib file for this cell layout, so just add the button in your contentView method and give it a known tag.
In your button's action method you can find out which row of the table the button was in by using the locationInView: and indexPathForRowAtPoint: methods:
CGPoint hit = [sender locationInView:self.tableView];
NSIndexPath *hitRow = [self.tableView indexPathForRowAtPoint:hit];
Also, note that setting a view's .hidden property to YES is probably less effort that setting its frame to CGRectZero.
Ended up fixing the solution by doing the following simple code:
NSIndexPath *indexPath = [self.tableView indexPathForCell:(UITableViewCell *)[[sender superview]superview]];
I used the UIButton sender to get the cell that it was within. I also pulled out all the modifications of the .tag's and kept them at the same number.

Issue with setting Tag for button in sectioned UITableView

I have two buttons inside sectioned tableview cell thumbs up and thumbs down. Initially image of both button is not selected. When I select thumbs up button its image become thumbs up selected and other one become thumbsdown not selected and vice versa.
//Number of sections
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
NSLog(#"mod:numberOfSectionsInTableView");
NSLog(#"[preferences count]=%d",[preferences count]);
return [preferences count];
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [self.choices count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView
cellForRowAtIndexPath:(NSIndexPath *)indexpath
{
NSLog(#"cellForRowAtIndexPath: DISPLAY TEST");
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:CellIdentifier] autorelease];
NSLog(#"Text is: %#", [choices objectAtIndex:indexpath.row]);
NSLog(#"CHOICE AT INDEX PATH IS: %#",[choices objectAtIndex:indexpath.row %[choices count]]);
cell.textColor = [UIColor whiteColor];
cell.backgroundColor = [UIColor blackColor];
// Thumbs up button.
//UIButton *thumbsUp = [[UIButton alloc]init];
thumbsUp = [UIButton buttonWithType:UIButtonTypeCustom];
[thumbsUp setTag:(indexpath.row+(indexpath.section * 50))];
[thumbsUp addTarget:self action:#selector(thumbUp_ButtonClicked:event:)
forControlEvents:UIControlEventTouchUpInside];
[thumbsUp setTitle:#"" forState:UIControlStateNormal];
thumbsUp.frame = CGRectMake(150.0, 20, 20, 15);
[thumbsUp setBackgroundImage:[UIImage imageNamed:#"thumbsup_not_selected.png"]
forState:UIControlStateNormal];
//NSLog(#"------------------>TAG TEST : %d",(indexpath.row+(indexpath.section * 50)));
[cell.contentView addSubview:thumbsUp];
// Thumbs down button
thumbsDown = [UIButton buttonWithType:UIButtonTypeCustom];
[thumbsDown addTarget:self action:#selector(thumbDown_ButtonClicked:event:)
forControlEvents:UIControlEventTouchUpInside];
[thumbsDown setTitle:#"" forState:UIControlStateNormal];
thumbsDown.frame = CGRectMake(200, 20, 20, 15);
[thumbsDown setTag:indexpath.row+120];
[cell.contentView addSubview:thumbsDown];
[cell setSelectionStyle:UITableViewCellSelectionStyleNone];
[thumbsDown setBackgroundImage:[UIImage imageNamed:#"thumbsdown_not_selected.png"]
forState:UIControlStateNormal];
}
NSLog(#"------------> TAG TEST %d",thumbsUp.tag);
cell.text = [choices objectAtIndex:(indexpath.row % [choices count])];
NSLog(#"HELLO FOR TESTING");
return cell;
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
NSString *sectionTitle = [self tableView:tableView titleForHeaderInSection:section];
if (sectionTitle == nil) {
return nil;
}
// Create label with section title
UILabel *label = [[[UILabel alloc] init] autorelease];
label.frame = CGRectMake(15, 10, 300, 25);
label.backgroundColor = [UIColor clearColor];
label.textColor = [UIColor blackColor];
label.shadowColor = [UIColor whiteColor];
label.shadowOffset = CGSizeMake(0.0, 1.0);
label.font = [UIFont boldSystemFontOfSize:16];
label.textAlignment = UITextAlignmentLeft;
label.text = sectionTitle;
// Create header view and add label as a subview
UIView *view = [[UIView alloc] initWithFrame:CGRectMake(12, 0, 300, 60)];
[view autorelease];
[view addSubview:label];
//[view addSubview:segmentedControl];
view.backgroundColor = [UIColor grayColor];
return view;
}
//Thumbs Up Button Action
- (IBAction)thumbUp_ButtonClicked:(id)sender event:(id)event
{
NSLog(#"Thumbs Up Check!");
UIButton *button = (UIButton *)sender;
UITableViewCell *cell = (UITableViewCell *) [[button superview] superview];
NSIndexPath *indexPath = [myTable indexPathForCell:cell];
NSLog(#"indexpath =%d",indexPath.row);
//[button setTag:indexPath.row+(indexPath.section * 50)];
int cTag = [sender tag];
NSLog(#"------>TAG : %d", cTag);
NSLog(#"------> Calculated TAG %d",indexPath.row+(indexPath.section * 50));
if(cTag == (indexPath.row+(indexPath.section * 50)))
{
NSLog(#"BUTTON COUNT:");
[button setBackgroundImage:[UIImage imageNamed:#"thumbsup_selected.png"]
forState:UIControlStateNormal];
}enter code here
NSInteger section = indexPath.section;
NSInteger row = indexPath.row;
//int row = button.tag;
NSLog(#"SECTION IS:%d",section);
NSLog(#"ROW IS: %d",row);
NSArray *array = cell.contentView.subviews;
NSLog(#"NUMBER OF OBJECTS: %d",[array count]);
UIButton *test = (UIButton *)[array objectAtIndex:2];
[test setBackgroundImage:[UIImage imageNamed:#"thumbsdown_not_selected.png"]forState:UIControlStateNormal];
}
Due to issue with tag of button while I change image of one button several buttons are changing.
If any one can please find a solution it will be helpful.... tag is setting for buttons in sections which we can view.
If the Tableview is not sectioned its working well.
Your problem might be the fact that you're setting the variable only if the cell is newly created. Perhaps the sectioning has an impact on how many cells are affected. Try pulling your thumbs up / thumbs down code out of the if (cell == nil) block and see if that has an effect.

Issue with button tag in sectioned UITableView

I have two buttons inside sectioned tableview cell thumbs up and thumbs down.
Initially image of both button is not selected. When I select thumbs up button its image become thumbs up selected and other one become thumbsdown not selected and vice versa.
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
enter code hereNSLog(#"mod:numberOfSectionsInTableView");
NSLog(#"[preferences count]=%d",[preferences count]);
return [preferences count];
}
-(NSInteger)tableView:(UITableView *)tableView
numberOfRowsInSection:(NSInteger)section
{enter code here
enter code herereturn [self.choices count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView
cellForRowAtIndexPath:(NSIndexPath *)indexpath
{
NSLog(#"cellForRowAtIndexPath: DISPLAY TEST");
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:CellIdentifier] autorelease];
NSLog(#"Text is: %#", [choices objectAtIndex:indexpath.row]);
NSLog(#"CHOICE AT INDEX PATH IS: %#",[choices objectAtIndex:indexpath.row %[choices count]]);
cell.textColor = [UIColor whiteColor];
cell.backgroundColor = [UIColor blackColor];
// Thumbs up button.
//UIButton *thumbsUp = [[UIButton alloc]init];
thumbsUp = [UIButton buttonWithType:UIButtonTypeCustom];
[thumbsUp setTag:(indexpath.row+(indexpath.section * 50))];
[thumbsUp addTarget:self
action:#selector(thumbUp_ButtonClicked:event:)
forControlEvents:UIControlEventTouchUpInside];
[thumbsUp setTitle:#"" forState:UIControlStateNormal];
thumbsUp.frame = CGRectMake(150.0, 20, 20, 15);
[thumbsUp setBackgroundImage:[UIImage imageNamed:#"thumbsup_not_selected.png"]
forState:UIControlStateNormal];
//NSLog(#"------------------>TAG TEST : %d",(indexpath.row+(indexpath.section * 50)));
[cell.contentView addSubview:thumbsUp];
// Thumbs down button
thumbsDown = [UIButton buttonWithType:UIButtonTypeCustom];
[thumbsDown addTarget:self
action:#selector(thumbDown_ButtonClicked:event:)
forControlEvents:UIControlEventTouchUpInside];
[thumbsDown setTitle:#"" forState:UIControlStateNormal];
thumbsDown.frame = CGRectMake(200, 20, 20, 15);
[thumbsDown setTag:indexpath.row+120];
[cell.contentView addSubview:thumbsDown];
[cell setSelectionStyle:UITableViewCellSelectionStyleNone];
[thumbsDown setBackgroundImage:[UIImage imageNamed:#"thumbsdown_not_selected.png"]forState:UIControlStateNormal];
}
NSLog(#"------------> TAG TEST %d",thumbsUp.tag);
cell.text = [choices objectAtIndex:(indexpath.row % [choices count])];
NSLog(#"HELLO FOR TESTING");
return cell;
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
NSString *sectionTitle = [self tableView:tableView titleForHeaderInSection:section];
if (sectionTitle == nil) {
return nil;
}
// Create label with section title
UILabel *label = [[[UILabel alloc] init] autorelease];
label.frame = CGRectMake(15, 10, 300, 25);
label.backgroundColor = [UIColor clearColor];
label.textColor = [UIColor blackColor];
label.shadowColor = [UIColor whiteColor];
label.shadowOffset = CGSizeMake(0.0, 1.0);
label.font = [UIFont boldSystemFontOfSize:16];
label.textAlignment = UITextAlignmentLeft;
label.text = sectionTitle;
// Create header view and add label as a subview
UIView *view = [[UIView alloc] initWithFrame:CGRectMake(12, 0, 300, 60)];
[view autorelease];
[view addSubview:label];
//[view addSubview:segmentedControl];
view.backgroundColor = [UIColor grayColor];
return view;
}
//Thumbs Up Button Action
- (IBAction)thumbUp_ButtonClicked:(id)sender event:(id)event
{
NSLog(#"Thumbs Up Check!");
UIButton *button = (UIButton *)sender;
UITableViewCell *cell = (UITableViewCell *) [[button superview] superview];
NSIndexPath *indexPath = [myTable indexPathForCell:cell];
NSLog(#"indexpath =%d",indexPath.row);
//[button setTag:indexPath.row+(indexPath.section * 50)];
int cTag=[sender tag];
NSLog(#"------>TAG : %d", cTag);
NSLog(#"------> Calculated TAG %d",indexPath.row+(indexPath.section * 50));
if(cTag == (indexPath.row+(indexPath.section * 50)))
{
NSLog(#"BUTTON COUNT:");
[button setBackgroundImage:[UIImage imageNamed:#"thumbsup_selected.png"]
forState:UIControlStateNormal];
}
NSInteger section = indexPath.section;
NSInteger row = indexPath.row;
//int row = button.tag;
NSLog(#"SECTION IS:%d",section);
NSLog(#"ROW IS: %d",row);
NSArray *array = cell.contentView.subviews;
NSLog(#"NUMBER OF OBJECTS: %d",[array count]);
UIButton *test = (UIButton *)[array objectAtIndex:2];
[test setBackgroundImage:[UIImage imageNamed:#"thumbsdown_not_selected.png"]forState:UIControlStateNormal];
}
Due to issue with tag of button while I change image of one button several buttons are changing. If any one can please find a solution it will be helpful....
This is a common occurrence due to the fact that the table view cells are recycled. Your scheme with the button tags is rather convoluted and error prone.
It would make more sense to keep track of the ThumbsUp/Down state of each cell in your table view's datatsource data model. Then, in cellForRowAtIndexPath: set each button state explicitly.
BTW: cell.text and cell.textColor are deprecated. You should use the properties of cell.textLabel.

UITableViewCell repeats after scrolling

I am not sure why my UITableViewCell's are repeating after the user scrolls?
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"Cell";
ChartlyCell *cell = (ChartlyCell*)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
//cell = [[[ChartlyCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
cell = [[[ChartlyCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier andDelegate:self] autorelease];
}
ChartlyObject *myChartlyObject;
myChartlyObject = [self.items objectAtIndex:indexPath.row];
cell.usernameLabel.text = myChartlyObject.userName;
cell.bodyLabel.text = myChartlyObject.chart_message;
[cell.messageLabel setText: myChartlyObject.chart_message];
cell.timeLabel.text = [Utils toShortTimeIntervalStringFromStockTwits: myChartlyObject.created_at];
[cell.chartImage loadImageFromURL:[NSURL URLWithString:myChartlyObject.imageThumbnail]];
return cell;
}
This is how the cell is being created:
-(id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier andDelegate:(id<NLabelDelegate>)ndelegate{
if ((self = [super initWithStyle:style reuseIdentifier:reuseIdentifier])) {
// Initialization code
CGRect rect;
rect = CGRectMake(77, 5, 200, 20); //CGRectMake(10, 5, 200, 20);
usernameLabel = [[UILabel alloc] initWithFrame:rect];
//usernameLabel.backgroundColor = backgroundColor;
usernameLabel.font = [Utils getBoldSystemFontWithSize:14];
usernameLabel.textColor = [UIColor colorWithRed:.368 green:.741 blue:.784 alpha:1];
[self.contentView addSubview: usernameLabel];
rect = CGRectMake(277, 5, 38, 20);
timeLabel = [[UILabel alloc] initWithFrame:rect];
timeLabel.textAlignment = UITextAlignmentRight;
//timeLabel.backgroundColor = backgroundColor;
timeLabel.font = [Utils getBoldSystemFontWithSize:14];
timeLabel.textColor = [UIColor colorWithRed:.98 green:.65 blue:.01 alpha:1];
[self.contentView addSubview: timeLabel];
/*rect = CGRectMake(77, 25, 238, 68); //CGRectMake(10, 50, 238, 68);
bodyLabel = [[UILabel alloc] initWithFrame:rect];
bodyLabel.font = [Utils getSystemFontWithSize:10];
bodyLabel.numberOfLines = 3;
bodyLabel.lineBreakMode = UILineBreakModeWordWrap;
bodyLabel.textColor = [UIColor blackColor];
bodyLabel.backgroundColor = [UIColor clearColor];
[self.contentView addSubview: bodyLabel];*/
rect = CGRectMake(77, 25, 238, 68);
messageLabel = [[NLabel alloc] initWithFrame:rect andDelegate:ndelegate];
[messageLabel setOpaque:NO];
[messageLabel setBackgroundColor: [UIColor blackColor]];
//[messageLabel setTotalheight:68];
[self.contentView addSubview: messageLabel];
rect = CGRectMake(13, 10, 48, 48);
chartImage = [[AsyncImageView alloc]initWithFrame:rect];
[self.contentView addSubview: chartImage];
}
return self;
}
UPDATE:
What is odd, is that if I uncomment the bodyLabel block and comment out the messageLabel block the repeating cells don't appear anymore. I am not sure why and would still like to find a resolution
UPDATE #2
Only messageLabel gets repeated. All of the other labels do NOT repeat. Why is this?
Because you are re-using tablecells for proper memory management as you should be doing via dequeueReusableCellWithIdentifier :) This way you don't have a unique cell for every single cell you need. Instead you only have about 5 or 6 that get re-used over and over during scrolling.
When the cell comes back into view, you need to reset the state (i.e. update the info, labels, images, etc) of each cell based on whatever cell came into view.
One thing you can do is to remove all the views in the cell.contentView after you create the cell or dequeue it. Alternatively, you can create a custom cell with attributes for the labels that you can set to different values when you scroll down.