how to maintain state of uibutton in table view - objective-c

I have a table view in that I am using a custom cell. I have two buttons on each table view cell named "edit" and "cancel" both have images in cellForRow. What I want that when user clicks on edit button at same time same rows cancel button should change its image. Code is Working but it not changing same rows cancel button image. Its changing another rows cancel button image. How to maintain state of each button.
Here Is Code
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
simpleTableIdentifier = #"MenuNameCell";
MenuNameCell *cell = (MenuNameCell *)[tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier];
if (cell== nil) {
NSArray *nib = [[NSBundle mainBundle] loadNibNamed:#"MenuNameCell" owner:self options:nil];
cell = [nib objectAtIndex:0];
NSLog(#"---------new cell agin");
}
else
[cell.contentView.subviews makeObjectsPerformSelector:#selector(removeFromSuperview)];
// Creating Label Menu Name
_nameLabel = [[UILabel alloc] initWithFrame:CGRectMake(8, 11, 82, 21)];
_nameLabel.backgroundColor = [UIColor clearColor];
_nameLabel.text = [_hotel._orderedMenus objectAtIndex:indexPath.row];
// Creating Label Menu Cost
_amountMenu = [[UILabel alloc] initWithFrame:CGRectMake(167, 13, 44, 21)];
_amountMenu.backgroundColor = [UIColor clearColor];
_amountMenu.text = [[_hotel._menuPrices objectAtIndex:indexPath.row] stringValue];
// Creating Text Field For Order Quantity
_textFieldQuantity = [[UITextField alloc] initWithFrame:CGRectMake(125,14,42,21)];
_textFieldQuantity.userInteractionEnabled = NO;
_textFieldQuantity.text = [[_hotel._selectedQuantity objectAtIndex:indexPath.row] stringValue];
//Creating Button For CANCEL Order
_cancelButton = [UIButton buttonWithType:UIButtonTypeCustom];
[_cancelButton setFrame:CGRectMake(265, 13, 25, 28)];
[_cancelButton setBackgroundImage:[UIImage imageNamed:#"cancel.png"] forState:UIControlStateNormal];
[_cancelButton setTag:indexPath.row];
[_cancelButton addTarget:self action:#selector(cancelOreder:) forControlEvents:UIControlEventTouchUpInside];
// Creating Button For Check Order
_checkButton = [UIButton buttonWithType:UIButtonTypeCustom];
[_checkButton setFrame:CGRectMake(232, 13, 25, 28)];
[_checkButton setTag:indexPath.row];
[_checkButton setBackgroundImage:[UIImage imageNamed:#"edit.png"]forState:UIControlStateNormal];
[_checkButton addTarget:self action:#selector(editQuantity:) forControlEvents:UIControlEventTouchUpInside];
// Adding All To Content View
[cell.contentView addSubview:_nameLabel];
[cell.contentView addSubview:_amountMenu];
[cell.contentView addSubview:_textFieldQuantity];
[cell.contentView addSubview:_checkButton];
[cell.contentView addSubview:_cancelButton];
//objc_setAssociatedObject(_checkButton, iindex, indexPath,OBJC_ASSOCIATION_RETAIN );
return cell;
}
-(void)editQuantity:(id)sender{
NSLog(#"count of the array is----%d",[imageViewArray count]);
button = (UIButton *)sender;
row = button.tag;
NSLog(#"---rowww%d",row);
_textFieldQuantity.userInteractionEnabled = YES;
UIImage *buttonImage = [UIImage imageNamed:#"edit_over.png"];
[button setBackgroundImage:buttonImage forState:UIControlStateNormal];
UIImage *buttonImageCancel = [UIImage imageNamed:#"check.png"];
[_cancelButton setBackgroundImage:buttonImageCancel forState:UIControlStateNormal];
_cancelButton.tag = 0;
}
-(void)cancelOreder:(id)sender{
button = (UIButton *)sender;
row = button.tag;
NSLog(#"The Row Selected iS At Cancel Order ISSSS----%d", row);
if (_cancelButton.tag == 0){
_textFieldQuantity.userInteractionEnabled = NO;
UIImage *buttonImageCancel = [UIImage imageNamed:#"check_over.png"];
[_cancelButton setBackgroundImage:buttonImageCancel forState:UIControlStateNormal];
UIImage *buttonImageCancel1 = [UIImage imageNamed:#"cancel.png"];
[_cancelButton setBackgroundImage:buttonImageCancel1 forState:UIControlStateNormal];
UIImage *buttonImage = [UIImage imageNamed:#"edit.png"];
[_checkButton setBackgroundImage:buttonImage forState:UIControlStateNormal];
_cancelButton.tag = 1;
}
else
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"iHomeDelivery" message:#"Do You Want To Cancel the Order" delegate:self cancelButtonTitle:#"Ok" otherButtonTitles:nil];
[alert show];
[alert release];
}
}

Try to make _cancelButton and _checkButton with different tag in the same cell, I think it is puzzle to make both of them with same tag in the same row.

Give different tag for each buttons first like :
[_checkButton setTag:indexPath.row];
[_cancelButton setTag:indexPath.row+100];
and in your editQuantity: method
button = (UIButton *)sender;
row = button.tag;
NSIndexPath *currentIndexPath = [NSIndexPath indexPathForRow:row inSection:0];
UITableViewCell *newCell = [yourTable cellForRowAtIndexPath:currentIndexPath];
newCancelButton = (UIButton *)[newCell.contentView viewWithTag:row+100];
[newCancelButton setBackgroundImage:buttonImageCancel forState:UIControlStateNormal];
Do same in your cancelOreder: method to change image of _checkButton.
Also, use this for remove all subViews,
[cell.contentView.subviews makeObjectsPerformSelector:#selector(removeFromSuperview)];

please try this solution
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"CELL_ID"];
if(cell == nil)
{
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:#"CELL_ID"];
UIButton *_cancelButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[_cancelButton setFrame:CGRectMake(65, 13, 100, 28)];
[_cancelButton setTitle:#"Cancel" forState:UIControlStateNormal];
[_cancelButton setTitleColor:[UIColor greenColor] forState:UIControlStateNormal];
[_cancelButton addTarget:self action:#selector(cancelOreder:) forControlEvents:UIControlEventTouchUpInside];
[_cancelButton setTag:1];
UIButton *_checkButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[_checkButton setFrame:CGRectMake(200, 13, 100, 28)];
[_checkButton setTitle:#"Check" forState:UIControlStateNormal];
[_checkButton setTitleColor:[UIColor greenColor] forState:UIControlStateNormal];
[_checkButton addTarget:self action:#selector(editQuantity:) forControlEvents:UIControlEventTouchUpInside];
[_checkButton setTag:2];
[cell.contentView addSubview:_checkButton];
[cell.contentView addSubview:_cancelButton];
}
return cell;
}
-(void) cancelOreder:(id)sender
{
UITableViewCell *cell = (UITableViewCell *)[(UIButton *)sender superview];
UIButton *btn = (UIButton *)[cell viewWithTag:2];
if(btn != nil)
{
[btn setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
}
}
-(void) editQuantity:(id)sender
{
UITableViewCell *cell = (UITableViewCell *)[(UIButton *)sender superview];
UIButton *btn = (UIButton *)[cell viewWithTag:1];
if(btn != nil)
{
[btn setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
}
}
in this example i cheange text color of label you can change image,hope this will help you

Related

Button's Tag are same in TableView

I add view for header, here is my code:
-(UIView*)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
UIView *view = [[UIView alloc] init];
view.layer.borderWidth = 0.5;
view.layer.borderColor = [UIColor colorWithRed:127.0/255.0 green:229.0/255.0 blue:232.0/255.0 alpha:1.0].CGColor;
view.backgroundColor = [UIColor clearColor];
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(30, 0, 150, 50)];
label.text = sectionArray[section];
label.backgroundColor = [UIColor clearColor];
label.textColor = [UIColor colorWithRed:0.0 green:122.0/255.0 blue:1.0 alpha:1.0];
button = [[UIButton alloc] initWithFrame:CGRectMake(self.myTableView.frame.size.width - 50, 15, 20, 20)];
[button setImage:[UIImage imageNamed:#"down"] forState:UIControlStateNormal];
button.tag = section;
[button addTarget:self action:#selector(extentFunction) forControlEvents:UIControlEventTouchUpInside];
[view addSubview:label];
[view addSubview:button];
return view;
}
-(void)extentFunction {
switch (button.tag) {
case 0:
NSLog(#"0");
break;
case 1:
NSLog(#"1");
break;
case 2:
NSLog(#"2");
break;
case 3:
NSLog(#"3");
break;
default:
break;
}
}
The question is: the button's tag is same of each header, not the section integer (ex: first header button's tag is 0; second header button's tag is 1)that I want.
What should I do?
As first look its clear issue of local & global variable.
You need to define your button as local variable and use button action sender as button object and get tag from that button.
Look at below code I think it will help you to understand your issue:
-(UIView*)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
UIView *view = [[UIView alloc] init];
view.layer.borderWidth = 0.5;
view.layer.borderColor = [UIColor colorWithRed:127.0/255.0 green:229.0/255.0 blue:232.0/255.0 alpha:1.0].CGColor;
view.backgroundColor = [UIColor clearColor];
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(30, 0, 150, 50)];
label.text = sectionArray[section];
label.backgroundColor = [UIColor clearColor];
label.textColor = [UIColor colorWithRed:0.0 green:122.0/255.0 blue:1.0 alpha:1.0];
//Make Your Button local object not global
UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(self.myTableView.frame.size.width - 50, 15, 20, 20)];
[button setImage:[UIImage imageNamed:#"down"] forState:UIControlStateNormal];
button.tag = section;
[button addTarget:self action:#selector(extentFunction) forControlEvents:UIControlEventTouchUpInside];
[view addSubview:label];
[view addSubview:button];
return view;
}
-(IBAction)btnClick:(UIButton*)sender{
switch (sender.tag) {
case 0:
NSLog(#"0");
break;
case 1:
NSLog(#"1");
break;
case 2:
NSLog(#"2");
break;
case 3:
NSLog(#"3");
break;
default:
break;
}
}
Let me know if its working fine.
This is your custom button code which is correct.
UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(self.myTableView.frame.size.width - 50, 15, 20, 20)];
[button setImage:[UIImage imageNamed:#"down"] forState:UIControlStateNormal];
button.tag = section;
[button addTarget:self action:#selector(extentFunction) forControlEvents:UIControlEventTouchUpInside];
But you also need to add its sender and event to get the touch location of your button like below code.
[button addTarget:self action:#selector(extentFunction:event:) forControlEvents:UIControlEventTouchUpInside];
Now when you will click on button, extentFunction selector will get called. Now all you have to do is implement your button selector like below code.
-(void)extentFunction:(id)sender event:(id)event{
NSSet *touches = [event allTouches];
UITouch *touch = [touches anyObject];
CGPoint currentTouchPosition = [touch locationInView:_yourTableViewName];
NSIndexPath *indexPath = [_yourTableViewName indexPathForRowAtPoint: currentTouchPosition];
NSLog(#"%ld",indexPath.section);
}
Hope this will help you out.

Cannot remove dynamic UIButton

The UIButton is created under #implementation . I have to remove it after some functions but[button removeFromSuperview] doesn't work. How can I remove that?
#import "TabBar.h"
#import "CustomCell.h"
#interface TabBar ()
#end
#implementation TabBar
UILabel *title;
NSString *par;
UIButton *button;
NSMutableArray *backlist;
- (NSString *)documentsDirectory {
return [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
NSUserDomainMask, YES) lastObject];
}
-(void)tbl_info{
NSString *path = [[self documentsDirectory] stringByAppendingPathComponent:#"icd10.plist"];
self.dataList = [[NSMutableArray alloc] initWithContentsOfFile:path];
for (NSInteger i=[self.dataList count]-1; i>=0;i--) {
NSDictionary *d = [self.dataList objectAtIndex:i];
par=[d objectForKey:#"PARENTID"];
if(![par isEqualToString:self.val])
[self.dataList removeObjectAtIndex:i];
}
}
- (IBAction)ara:(id)sender{
[self tbl_info];
[self.tViewTab reloadData];
}
- (NSInteger)tableView:(UITableView *)tableView
numberOfRowsInSection:(NSInteger)section
{
return [self.dataList count];
}
- (CGFloat)tableView:(UITableView *)tableView
heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSString *name= [[self.dataList objectAtIndex:indexPath.row] objectForKey:#"NAME"];
CGSize maxSize = CGSizeMake(320/2, MAXFLOAT);
CGSize labelSize = [name sizeWithFont:[UIFont systemFontOfSize:14] constrainedToSize:maxSize lineBreakMode:NSLineBreakByWordWrapping];
if(labelSize.height>=63)
labelSize.height=63;
return labelSize.height+1;
}
- (UITableViewCell*)tableView:(UITableView *)tableView
cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *cellID = #"cellid";
CustomCell *cell = (CustomCell*)[tableView dequeueReusableCellWithIdentifier:cellID];
if (cell == nil)
{
cell = (CustomCell*)[[[NSBundle mainBundle]
loadNibNamed:#"CustomCell" owner:nil options:nil]
lastObject];
}
NSDictionary *d = [self.dataList objectAtIndex:indexPath.row];
cell.nameLabel.text = [d objectForKey:#"NAME"];
cell.cityLabel.text = [d objectForKey:#"CODE"];
cell.indexPath = indexPath;
CGSize maxSize = CGSizeMake(320/2, MAXFLOAT);
CGSize nameSize = [cell.nameLabel.text sizeWithFont:[UIFont systemFontOfSize:14] constrainedToSize:maxSize lineBreakMode:NSLineBreakByWordWrapping];
if(nameSize.height>=63)
nameSize.height=63;
cell.nameLabel.frame =CGRectMake(80, 0, 234, nameSize.height);
cell.cityLabel.text = [d objectForKey:#"CODE"];
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
NSDictionary *d = [self.dataList objectAtIndex:indexPath.row];
NSMutableDictionary *backprop = [[NSMutableDictionary alloc] init];
[backprop setObject:self.val forKey:#"id"];
[backprop setObject:title.text forKey:#"name"];
[backlist addObject:backprop];
//back button
button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[button addTarget:self action:#selector(touchEvent:) forControlEvents:UIControlEventTouchUpInside];
[button setTitle:title.text forState:UIControlStateNormal];
button.frame = CGRectMake(02.0, 02.0, 71, 32);
[self.view addSubview:button];
//parent and title label
[title setText:[d objectForKey:#"NAME"]];
self.val=[d objectForKey:#"ID"];
[self tbl_info];
[self.tViewTab reloadData];
}
-(void)touchEvent:(id)sender{
[title setText:[[backlist objectAtIndex:backlist.count-1] objectForKey:#"name" ]];
self.val= [[backlist objectAtIndex:backlist.count-1] objectForKey:#"id"];
[backlist removeObjectAtIndex:backlist.count-1];
if(backlist.count>0)
[button setTitle:[[backlist objectAtIndex:backlist.count-1] objectForKey:#"name" ] forState:UIControlStateNormal];
else
[button removeFromSuperview];
[self tbl_info];
[self.tViewTab reloadData];
}
- (void)viewDidLoad
{
[super viewDidLoad];
backlist =[[NSMutableArray alloc]init];
self.val=#"0";
[self tbl_info];
[self.tViewTab reloadData];
title =[[UILabel alloc]initWithFrame:CGRectMake(79.0, 07.0, 162, 21)];
title.text = #"ICD10 Kod Grupları"; //etc...
[self.view addSubview:title];
[title release];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
}
In place of this :
button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[button addTarget:self action:#selector(touchEvent:) forControlEvents:UIControlEventTouchUpInside];
[button setTitle:title.text forState:UIControlStateNormal];
button.frame = CGRectMake(02.0, 02.0, 71, 32);
[self.view addSubview:button];
Try this :
if (button != nil) {
button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[button addTarget:self action:#selector(touchEvent:) forControlEvents:UIControlEventTouchUpInside];
[button setTitle:title.text forState:UIControlStateNormal];
button.frame = CGRectMake(02.0, 02.0, 71, 32);
[self.view addSubview:button];
}
Or try this :
if (button != nil) {
[button removeFromSuperView];
[button release]; // dont write this in case of ARC
button = nil;
}
button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[button addTarget:self action:#selector(touchEvent:) forControlEvents:UIControlEventTouchUpInside];
[button setTitle:title.text forState:UIControlStateNormal];
button.frame = CGRectMake(02.0, 02.0, 71, 32);
[self.view addSubview:button];
Not a solution but a workaround:
Use
[sender removeFromSuperview];
or respectively, because sender is of type id and not UIView*:
[(UIButton*)sender removeFromSuperview];
But you could change sender to UIView* savely.
-(void)touchEvent:(UIView *)sender{
Some even put UIButton* in there. I personally don't like that but it is quite save if you know for sure that the message is sent by UIButtons only.
Another workaround would be to set the .tag property of the button and then fetch the real buttom from self.view by its tag.

Table View Cell Button Not Responding with it index position

I have Custom Table View Cell In That I Have Two UIButton and One Text Field Named As edit and cancel and one textField. When I Click on edit at same time TextFeild Interaction is Enabled And Cancel Button Image Should Change. Its Working Fine For Me!!
But When I am Clicking On Edit Button Another Cells Cancel bitton Image id Changed Automatically! I know that this happening because I'm reusing the cell!! But I'm not able to find a solution...
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
simpleTableIdentifier = #"MenuNameCell";
cell = (MenuNameCell *)[tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier];
if (!cell) {
NSArray *nib = [[NSBundle mainBundle] loadNibNamed:#"MenuNameCell" owner:self options:nil];
cell = [nib objectAtIndex:0];
NSLog(#"---------new cell agin");
}
else
{
for (UIView *view in [cell.contentView subviews])
[view removeFromSuperview];
NSLog(#"---------older use");
// _checkButton = (UIButton *)[cell.contentView viewWithTag:indexPath.row];
// _cancelButton = (UIButton *)[cell.contentView viewWithTag:indexPath.row];
}
// Creating Label Menu Name
_nameLabel = [[UILabel alloc] initWithFrame:CGRectMake(8, 11, 82, 21)];
_nameLabel.backgroundColor = [UIColor clearColor];
_nameLabel.text = [_hotel._orderedMenus objectAtIndex:indexPath.row];
// Creating Label Menu Cost
_amountMenu = [[UILabel alloc] initWithFrame:CGRectMake(167, 13, 44, 21)];
_amountMenu.backgroundColor = [UIColor clearColor];
_amountMenu.text = [[_hotel._menuPrices objectAtIndex:indexPath.row] stringValue];
// Creating Text Field For Order Quantity
_textFieldQuantity = [[UITextField alloc] initWithFrame:CGRectMake(125,14,42,21)];
_textFieldQuantity.userInteractionEnabled = NO;
_textFieldQuantity.text = [[_hotel._selectedQuantity objectAtIndex:indexPath.row] stringValue];
// Creating Button For Check Order
_checkButton = [UIButton buttonWithType:UIButtonTypeCustom];
[_checkButton setFrame:CGRectMake(232, 13, 25, 28)];
[_checkButton setBackgroundImage:[UIImage imageNamed:#"edit.png"]forState:UIControlStateNormal];
[_checkButton addTarget:self action:#selector(editQuantity:) forControlEvents:UIControlEventTouchUpInside];
[_checkButton setTag:indexPath.row];
// Creating Button For CANCEL Order
_cancelButton = [UIButton buttonWithType:UIButtonTypeCustom];
[_cancelButton setFrame:CGRectMake(265, 13, 25, 28)];
[_cancelButton setBackgroundImage:[UIImage imageNamed:#"cancel.png"] forState:UIControlStateNormal];
[_cancelButton addTarget:self action:#selector(cancelOreder:) forControlEvents:UIControlEventTouchUpInside];
[_cancelButton setTag:indexPath.row];
// Adding All To Call Content View
[cell.contentView addSubview:_nameLabel];
[cell.contentView addSubview:_amountMenu];
[cell.contentView addSubview:_textFieldQuantity];
[cell.contentView addSubview:_checkButton];
[cell.contentView addSubview:_cancelButton];
return cell;
}
Edit:
-(void)editQuantity:(id)sender
{
_textFieldQuantity.userInteractionEnabled = YES;
button = (UIButton *)sender;
row = button.tag;
NSLog(#"Check Button index is %d",row);
UIImage *buttonImage = [UIImage imageNamed:#"edit_over.png"];
[_checkButton setBackgroundImage:buttonImage forState:UIControlStateNormal];
UIImage *buttonImageCancel = [UIImage imageNamed:#"check.png"];
[_cancelButton setBackgroundImage:buttonImageCancel forState:UIControlStateNormal];
_cancelButton.tag = 0;
}
-(void)cancelOreder:(id)sender{
button = (UIButton *)sender;
row = button.tag;
NSLog(#"The Row Selected iS At Cancel Order ISSSS----%d", row);
if (_cancelButton.tag == 0){
_textFieldQuantity.userInteractionEnabled = NO;
UIImage *buttonImageCancel = [UIImage imageNamed:#"check_over.png"];
[_cancelButton setBackgroundImage:buttonImageCancel forState:UIControlStateNormal];
UIImage *buttonImageCancel1 = [UIImage imageNamed:#"cancel.png"];
[_cancelButton setBackgroundImage:buttonImageCancel1 forState:UIControlStateNormal];
UIImage *buttonImage = [UIImage imageNamed:#"edit.png"];
[_checkButton setBackgroundImage:buttonImage forState:UIControlStateNormal];
_cancelButton.tag = 1;
}
else
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"iHomeDelivery" message:#"Do You Want To Cancel the Order" delegate:self cancelButtonTitle:#"Ok" otherButtonTitles:nil];
[alert show];
[alert release];
}
}
Your problem is that _textFieldQuantity (and the others) is an instance variable. When editQuantity: and cancelOreder: are called the instance varialbe still has the same value that was set last time when adding a cell within cellForRowAtIndexPath: .
What could you do to fix it?
1st:
You could set the row in the tag of the button. Then, when the button is tapped on and the action is invoced get the tag and fetch the cell (you can call the table's cellForRowAtIndexPath method to get it. That is different from the delegate method that you implement) and then find the appropriate textField.
2nd:
A bit more work but probably smarter could be to implment a subclass of your table cell. Move the action methods to that very cell class. Doing so each button's action refers to an individual object wich is then the cell class and not the view controller. The cell class can have its own textField instance variables. It shoud even provide properties to the textField and other UIItems so that you can set their values in cellForRowAtIndexPath.
I would suggest the first solution as a quick starter. But for future use I strongly suggest to go the second way. That way will help you in similar situations in the future.

Issue With setting tag for Button 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
{
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];
}
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.
The reason is the bad use of the recycling/reuse mechanism (as with 75% of questions about UITableView…)
Go read the Table View Programming Guide in Apple's doc (and search SO and the web for any question related to tableview and the reuse mechanism)
Corrected the issue by creating buttons outside and inside if(cell == nil). Also created a mutable dictionary to keep the current state of the button.....

Reloading images in the buttons present in the table view

In my table view I have 4 UIButtons, 2 in each row of table view. Initially all the buttons have an image on them (they're hardcoded). Now there is a button in my app which when tapped replaces the images on the buttons with new ones using the setImage method and then reloads the table view. But unfortunately I am getting the old table view only i mean with old images. How can I get the new images on the buttons?
My cellForRowAtIndexPath implementation:-// 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];
// }
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
}
if(indexPath.row == 0)
{
button1=[[UIButton alloc] initWithFrame:CGRectMake(15,5,100,87)];
[button1 setImage:[UIImage imageNamed:#"BUTTON.png"] forState:UIControlStateNormal];
[button1 addTarget:self action:#selector(ClickTo:) forControlEvents:UIControlEventTouchUpInside];
[cell.contentView addSubview:self.button1];
button2=[[UIButton alloc] initWithFrame:CGRectMake(135,5,100,87)];
[button2 setImage:[UIImage imageNamed:#"TURN OFF.png"] forState:UIControlStateNormal];
[button2 addTarget:self action:#selector(ClickTo:) forControlEvents:UIControlEventTouchUpInside];
[cell.contentView addSubview:button2];
}
else if(indexPath.row == 1)
{
button3=[[UIButton alloc] initWithFrame:CGRectMake(15,5,100,87)];
[button3 setImage:[UIImage imageNamed:#"JUMP.png"] forState:UIControlStateNormal];
[button3 addTarget:self action:#selector(ClickTo:) forControlEvents:UIControlEventTouchUpInside];
[cell.contentView addSubview:button3];
button4=[[UIButton alloc] initWithFrame:CGRectMake(135,5,100,87)];
[button4 setImage:[UIImage imageNamed:#"CLOSE.png"] forState:UIControlStateNormal];
[button4 addTarget:self action:#selector(ClickTo:) forControlEvents:UIControlEventTouchUpInside];
[cell.contentView addSubview:button4];
}
else
{
// Do something here
}
return cell;
}
You are probably setting the image for the wrong state:
[myButton setImage:[UIImage imageNamed:#"myImage.png"] forState:UIControlStateNormal];
You need to set the correct value for UIControlStateNormal - where correct means the one that matches your buttons' current state(s).
It Seems that you have hardcoded images in cell for row method, so whenever you are reloading your tableview , they will have same images.
So If you like to change them then take a boolean varible and Update it like :
(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];
// }
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
}
if(indexPath.row == 0)
{
button1=[[UIButton alloc] initWithFrame:CGRectMake(15,5,100,87)];
[button1 setImage:[UIImage imageNamed:#"BUTTON.png"] forState:UIControlStateNormal];
[button1 addTarget:self action:#selector(ClickTo:) forControlEvents:UIControlEventTouchUpInside];
[cell.contentView addSubview:self.button1];
button2=[[UIButton alloc] initWithFrame:CGRectMake(135,5,100,87)];
[button2 setImage:[UIImage imageNamed:#"TURN OFF.png"] forState:UIControlStateNormal];
[button2 addTarget:self action:#selector(ClickTo:) forControlEvents:UIControlEventTouchUpInside];
[cell.contentView addSubview:button2];
}
else if(indexPath.row == 1)
{
button3=[[UIButton alloc] initWithFrame:CGRectMake(15,5,100,87)];
[button3 setImage:[UIImage imageNamed:#"JUMP.png"] forState:UIControlStateNormal];
[button3 addTarget:self action:#selector(ClickTo:) forControlEvents:UIControlEventTouchUpInside];
[cell.contentView addSubview:button3];
button4=[[UIButton alloc] initWithFrame:CGRectMake(135,5,100,87)];
[button4 setImage:[UIImage imageNamed:#"CLOSE.png"] forState:UIControlStateNormal];
[button4 addTarget:self action:#selector(ClickTo:) forControlEvents:UIControlEventTouchUpInside];
[cell.contentView addSubview:button4];
}
else
{
// Do something here
}
if(myflag)
{
[button1 setImage:[UIImage imageNamed:#"changedImage1"] forState:UIControlStateNormal];
[button2 setImage:[UIImage imageNamed:#"changedImage2"] forState:UIControlStateNormal];
[button3 setImage:[UIImage imageNamed:#"changedImage3"] forState:UIControlStateNormal];
[button4 setImage:[UIImage imageNamed:#"changedImage4"] forState:UIControlStateNormal];
}
return cell;
}
// In Click to Method Set myflag yes and reload table
-(void)ClickTo:(IBAction )sender
{
myflag=YES;
[tableview reloadData];
}