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

I am creating an app in which i have a UITableView and the table view each cell are having an UIView and the UIView contains two custom UIButton and two UILabel(all with same tag) the value of label coming from XML parsing. Now i have to do is that when i click any one button then it calls a method with the tag of the button then i want to fetch the value of the both labels of that cell and use that value.
But when i am doing this it is not happen by calling a method i am getting the tag value but when i try to get the label value then i am unable to get.
Is there any way to get the value of that?
Code of the method that i am using to get the label value...
-(void)swapButtonPressed:(id)sender {
NSInteger a= [sender tag];
UITableViewCell *cell;
NSIndexPath *indexPath = [self.tableView indexPathForCell:(UITableViewCell *) [[sender superview] superview]];
NSLog(#"%d", indexPath.row);
UIView *viewForCell = (UIView *)[cell.contentView viewWithTag:a];
UILabel *label = (UILabel *)[viewForCell viewWithTag:a];
NSString *str = label.text;
}
Code of the method cellForRowAtIndexPath....
- (UITableViewCell *)tableView:(UITableView *)tableView1 cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *identifier = #"Cell";
UITableViewCell *cell = [tableView1 dequeueReusableCellWithIdentifier:identifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier] autorelease];
}
cell.selectionStyle = UITableViewCellSelectionStyleNone;
NSDictionary *dict = [appDelegate.webDataList objectAtIndex:indexPath.row];
tableView.backgroundColor = [UIColor colorWithRed:0.39 green:0.39 blue:0.39 alpha:0.39];
if([appDelegate.dataArray count]>0){
imgView.backgroundColor = [UIColor clearColor];
imgView =[[UIView alloc ] initWithFrame:CGRectMake(0,0,320,45)];
imgView.tag= indexPath.row;
[cell.contentView addSubview:imgView];
button=[UIButton buttonWithType:UIButtonTypeCustom];
button.frame=CGRectMake(291, 5, 19, 21);
img =[UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:#"swap_re" ofType:#"png"]];
[button setBackgroundImage:img forState:UIControlStateNormal];
[button addTarget:self action:#selector(swapButtonPressed:) forControlEvents:UIControlEventTouchUpInside];
button.tag= indexPath.row;
[imgView addSubview:button];
button=[UIButton buttonWithType:UIButtonTypeCustom];
button.frame=CGRectMake(-25, 5, 19, 21);
img =[UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:#"swap_re" ofType:#"png"]];
[button setBackgroundImage:img forState:UIControlStateNormal];
[button addTarget:self action:#selector(swapButtonPressed:) forControlEvents:UIControlEventTouchUpInside];
button.tag= indexPath.row;
[imgView addSubview:button];
button=[UIButton buttonWithType:UIButtonTypeCustom];
button.frame=CGRectMake(5, 7, 19, 21);
button.tag = indexPath.row;
img =[UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:#"delete" ofType:#"png"]];
[button setBackgroundImage:img forState:UIControlStateNormal];
[button addTarget:self action:#selector(deleteButtonPressed:) forControlEvents:UIControlEventTouchUpInside];
[imgView addSubview:button];
NSArray *arr = [[appDelegate.dataArray objectAtIndex:indexPath.row] componentsSeparatedByString:#"/"];
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(34,9,140,20)];
label.text = [arr objectAtIndex:1];
label.tag = indexPath.row;
[label setFont:[UIFont fontWithName:#"Georgia" size:14]];
[label setNumberOfLines:0];
label.textAlignment = UITextAlignmentLeft;
label.textColor = [UIColor whiteColor];
label.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleHeight;
label.backgroundColor = [UIColor clearColor];
[imgView addSubview:label];
[label release];
label = [[UILabel alloc] initWithFrame:CGRectMake(181, 7, 75, 20)];
label.tag = indexPath.row;
label.text = [dict1 objectForKey:#"time"];
[label setFont:[UIFont fontWithName:#"Georgia" size:16.0]];
label.textAlignment = UITextAlignmentLeft;
[label setBackgroundColor:[UIColor clearColor]];
label.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleHeight;
[label setTextColor:[UIColor whiteColor]];
[imgView addSubview:label];
[label release];
}
return cell;
}

I see two problems:
Tags need to be > 0 so you can't use indexPath.row directly.
Tags need to be unique within a superview
As #Kenny suggests, getting the indexPath from the cell and accessing the data source directly is generally more reliable. If you want to get values from the objects in the cell use unique tags > 0. I usually define an enum for tags within a subview to make things more readable.

I think that viewWithTag is recursive, so in your code that would mean that you get the label back in the first call to it, and nil in the second call. So perhaps this would work:
UILabel *label = (UILabel *)[cell.contentView viewWithTag:a];
NSString *str = label.text;
However, I'd recommend you get the value from your model object where you probably got it when you set the string on the button in the first place, something like this:
NSIndexPath *indexPath = [self.tableView indexPathForCell:(UITableViewCell *) [[sender superview] superview]];
TheObect *obj = [myobjects objectAtIndex:indexPath.row];
NSString *string = obj.name;

Related

How to fix a Receiver in message expression is an uninitialized value warning

I'm receiving the following error message for some code that creates a UIButton. How would I go about initialising this to fix this error that Analyzer warned me about:
Logic error: Receiver in message expression is an uninitialized value
the error occurs on the line in bold
// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UILabel *textLabel;
UILabel *detailTextLabel;
UIButton *button;
UIFont *cellFont = [UIFont boldSystemFontOfSize:10.0];
UIFont *detailCellFont = [UIFont fontWithName:#"Helvetica" size:8.0];
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
cell.selectionStyle = UITableViewCellSelectionStyleNone;
// Initialize API title UILabel
textLabel = [[[UILabel alloc] initWithFrame:CGRectZero] autorelease];
textLabel.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleRightMargin;
textLabel.tag = TITLE_TAG;
textLabel.font = cellFont;
[cell.contentView addSubview:textLabel];
// Initialize API description UILabel
detailTextLabel = [[[UILabel alloc] initWithFrame:CGRectZero] autorelease];
detailTextLabel.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleRightMargin;
detailTextLabel.tag = DESCRIPTION_TAG;
detailTextLabel.font = detailCellFont;
detailTextLabel.textColor = [UIColor blackColor];
detailTextLabel.lineBreakMode = UILineBreakModeWordWrap;
detailTextLabel.numberOfLines = 0;
[cell.contentView addSubview:detailTextLabel];
// Initialize API button UIButton
button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
button.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleRightMargin;
[button setBackgroundImage:[[UIImage imageNamed:#"blueButton.png"]
stretchableImageWithLeftCapWidth:9 topCapHeight:9]
forState:UIControlStateNormal];
[button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
[button addTarget:self action:#selector(apiButtonClicked:) forControlEvents:UIControlEventTouchUpInside];
[cell.contentView addSubview:button];
} else {
textLabel = (UILabel *)[cell.contentView viewWithTag:TITLE_TAG];
detailTextLabel = (UILabel *)[cell.contentView viewWithTag:DESCRIPTION_TAG];
// For the button cannot search by tag since it is not constant
// and is dynamically used figure out which button is clicked.
// So instead we loop through subviews of the cell to find the button.
for (UIView *subview in cell.contentView.subviews) {
if([subview isKindOfClass:[UIButton class]]) {
button = (UIButton *)subview;
}
}
}
CGSize constraintSize = CGSizeMake(280.0f, MAXFLOAT);
// The API title
NSString *cellText = [[apiMenuItems objectAtIndex:indexPath.row] objectForKey:#"title"];
CGSize labelSize = [cellText sizeWithFont:cellFont
constrainedToSize:constraintSize
lineBreakMode:UILineBreakModeWordWrap];
textLabel.frame = CGRectMake(20, 2,
(cell.contentView.frame.size.width-40),
labelSize.height);
textLabel.text = cellText;
// The API description
NSString *detailCellText = [[apiMenuItems objectAtIndex:indexPath.row] objectForKey:#"description"];
CGSize detailLabelSize = [detailCellText sizeWithFont:detailCellFont
constrainedToSize:constraintSize
lineBreakMode:UILineBreakModeWordWrap];
detailTextLabel.frame = CGRectMake(20, (labelSize.height + 4),
(cell.contentView.frame.size.width-40),
detailLabelSize.height);
detailTextLabel.text = detailCellText;
// The API button
CGFloat yButtonOffset = labelSize.height + detailLabelSize.height + 15;
**button.frame = CGRectMake(20, yButtonOffset, (cell.contentView.frame.size.width-40), 44);**
[button setTitle:[[apiMenuItems objectAtIndex:indexPath.row] objectForKey:#"button"]
forState:UIControlStateNormal];
// Set the tag that will later identify the button that is clicked.
button.tag = indexPath.row;
return cell;
}
thanks for any help
Did you do something like this anywhere in your code?
UIButton* button = [UIButton buttonWithType:UIButtonTypeCustom];
(type might also be UIButtonRoundRect)
...or this:
UIButton* button = [[UIButton alloc] initWithType:UIButtonTypeCustom];
The error tell you that the button has noT been initialized.
Try change this line
UIButton *button;
To
UIButton *button = [[UIButton alloc] init]Autorelease]; //remove Autorelease if using ARC

Analyzer warning in Facebook API for iOS

here's the code from the APICallsViewController file and a couple of screenshots. my app is crashing and I'm not sure if this is the cause.
thanks for any help
// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UILabel *textLabel;
UILabel *detailTextLabel;
UIButton *button;
UIFont *cellFont = [UIFont boldSystemFontOfSize:14.0];
UIFont *detailCellFont = [UIFont fontWithName:#"Helvetica" size:12.0];
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
cell.selectionStyle = UITableViewCellSelectionStyleNone;
// Initialize API title UILabel
textLabel = [[[UILabel alloc] initWithFrame:CGRectZero] autorelease];
textLabel.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleRightMargin;
textLabel.tag = TITLE_TAG;
textLabel.font = cellFont;
[cell.contentView addSubview:textLabel];
// Initialize API description UILabel
detailTextLabel = [[[UILabel alloc] initWithFrame:CGRectZero] autorelease];
detailTextLabel.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleRightMargin;
detailTextLabel.tag = DESCRIPTION_TAG;
detailTextLabel.font = detailCellFont;
detailTextLabel.textColor = [UIColor darkGrayColor];
detailTextLabel.lineBreakMode = UILineBreakModeWordWrap;
detailTextLabel.numberOfLines = 0;
[cell.contentView addSubview:detailTextLabel];
// Initialize API button UIButton
button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
button.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleRightMargin;
[button setBackgroundImage:[[UIImage imageNamed:#"MenuButton.png"]
stretchableImageWithLeftCapWidth:9 topCapHeight:9]
forState:UIControlStateNormal];
[button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
[button addTarget:self action:#selector(apiButtonClicked:) forControlEvents:UIControlEventTouchUpInside];
[cell.contentView addSubview:button];
} else {
textLabel = (UILabel *)[cell.contentView viewWithTag:TITLE_TAG];
detailTextLabel = (UILabel *)[cell.contentView viewWithTag:DESCRIPTION_TAG];
// For the button cannot search by tag since it is not constant
// and is dynamically used figure out which button is clicked.
// So instead we loop through subviews of the cell to find the button.
for (UIView *subview in cell.contentView.subviews) {
if([subview isKindOfClass:[UIButton class]]) {
button = (UIButton *)subview;
}
}
}
CGSize constraintSize = CGSizeMake(280.0f, MAXFLOAT);
// The API title
NSString *cellText = [[apiMenuItems objectAtIndex:indexPath.row] objectForKey:#"title"];
CGSize labelSize = [cellText sizeWithFont:cellFont
constrainedToSize:constraintSize
lineBreakMode:UILineBreakModeWordWrap];
textLabel.frame = CGRectMake(20, 2,
(cell.contentView.frame.size.width-40),
labelSize.height);
textLabel.text = cellText;
// The API description
NSString *detailCellText = [[apiMenuItems objectAtIndex:indexPath.row] objectForKey:#"description"];
CGSize detailLabelSize = [detailCellText sizeWithFont:detailCellFont
constrainedToSize:constraintSize
lineBreakMode:UILineBreakModeWordWrap];
detailTextLabel.frame = CGRectMake(20, (labelSize.height + 4),
(cell.contentView.frame.size.width-40),
detailLabelSize.height);
detailTextLabel.text = detailCellText;
// The API button
CGFloat yButtonOffset = labelSize.height + detailLabelSize.height + 15;
button.frame = CGRectMake(20, yButtonOffset, (cell.contentView.frame.size.width-40), 44);
[button setTitle:[[apiMenuItems objectAtIndex:indexPath.row] objectForKey:#"button"]
forState:UIControlStateNormal];
// Set the tag that will later identify the button that is clicked.
button.tag = indexPath.row;
return cell;
}
The button variable is a local variable. Unless you are using ARC, it's not guaranteed to be initialised to anything. It could be nonsense. The analyser is warning you that it's not clear it has had a meaningful address assigned to by the time you attempt to send a message to it (the setter for the frame property is the message you are sending it).
Consider this: cell is not nil, and you don't find a button in its subviews. If this is the case, the application will reach the line in question without ever having assigned to the button variable. It could contain a pointer to absolutely anywhere. If you try to dereference the pointer to send a message to the object, you could be scribbling over memory anywhere in your application.
Now, it may be the case that you know it is guaranteed to find a subclass that is a button. But the analyser can't figure that out. So it warns you regardless.
You should initialise the button variable to nil. If there is the possibility of not finding a button, you should handle that case.
in the else statement the UIButton *button is not initialized. Look how in the if statement it is:
button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
but in the else initialization is missing. You may put after:
} else {
textLabel = (UILabel *)[cell.contentView viewWithTag:TITLE_TAG];
detailTextLabel = (UILabel *)[cell.contentView viewWithTag:DESCRIPTION_TAG];
button = (UIButton *)[cell.contentView viewWithTag:indexPath.row]; // <---- add this
And move this:
button.tag = indexPath.row;
before
[cell.contentView addSubview:button];
in the end of the if statement...

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

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

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.

Checkboxes in UITableView

I am trying to create a list of options with check boxes. I am using UITableView and adding custom type buttons to the table as checkboxes.
My code for cellForRowAtIndexPath method is pasted below:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
}
CGRect a=CGRectMake(0, 0, 310, 32);
UIImageView *aImg=[[UIImageView alloc] initWithFrame:a];
UIImageView *bImg=[[UIImageView alloc] initWithFrame:a];
aImg.image=[[[Resources getResources] getImageLoader] getMainMenuUnselectedImage];
bImg.image=[[[Resources getResources] getImageLoader] getLiveScoreSmallBg];
[aImg setContentMode:UIViewContentModeScaleToFill];
[bImg setContentMode:UIViewContentModeScaleToFill];
cell.backgroundView = [[UIView alloc] initWithFrame:a];
[cell.backgroundView addSubview:aImg];
cell.selectedBackgroundView=bImg;
cell.font = [UIFont boldSystemFontOfSize:16];
cell.selectedTextColor = [UIColor blackColor];
UIImage *checked = [UIImage imageNamed:#"check_filled.png"];
UIImage *unchecked = [UIImage imageNamed:#"check_empty.png"];
UIButton *button = [[UIButton buttonWithType:UIButtonTypeCustom] initWithFrame:CGRectMake(3, 3, 30, 30)];
[button addTarget:self action:#selector(buttonPressed) forControlEvents:UIControlEventTouchUpInside];
[button setImage: [UIImage imageNamed:#"check_filled.png"] forState: UIControlStateSelected];
[button setImage: [UIImage imageNamed:#"check_empty.png"] forState: UIControlStateNormal];
[button setEnabled:YES];
button.tag = indexPath.row;
[button setUserInteractionEnabled:YES];
[cell.contentView addSubview:button];
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(40, 3, 250, 17)];
label.font = [UIFont boldSystemFontOfSize:15];
label.backgroundColor = [UIColor clearColor];
label.text = [teamsList objectAtIndex:indexPath.row];
[cell.contentView addSubview:label];
[button release];
[label release];
[aImg release];
[bImg release];
return cell;
}
The problem is that when I run the program, the screen appears without buttons. Also, when I click any row, the program crashes.
There're some problems with your code which may be not relevant to your problem, but still...
You create cell contents each time cell is reused - so if you scroll your table back and forth the reused cells will contain multiple identical subviews - that's not what you want. To fixed that you must move creating contents to the creating cell block:
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
// Create cell contents here!
...
}
...
You must not release your button - since you create it with convenience method button is autoreleased
button = [[UIButton buttonWithType:UIButtonTypeCustom]
initWithFrame:CGRectMake(3, 3, 30, 30)];
This line may also cause problems:
[button addTarget:self action:#selector(buttonPressed) forControlEvents:UIControlEventTouchUpInside];
Here you set selector that receives no parameters. If your buttonPressed method declared is (most common way)
- (void) buttonPressed:(id)sender;
Then you must create selector as #selector(buttonPressed:) to indicate that it actually takes 1 parameter
- (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];
}
int i=indexPath.row;
ibutton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[ibutton setTitle:#"i" forState:UIControlStateNormal];
ibutton.frame = CGRectMake(430.0,40.0,100.0,60.0);
[cell.contentView addSubview:ibutton];
[ibutton setTag:indexPath.row];
NSLog(#"the button tag is %d",ibutton.tag);
[ibutton addTarget:self action:#selector(detailSubView:) forControlEvents:UIControlEventTouchUpInside];
addbutton=[UIButton buttonWithType:UIButtonTypeRoundedRect];
[addbutton setTitle:#"add" forState:UIControlStateNormal];
addbutton.frame=CGRectMake(560, 40, 100, 60);
[addbutton setTag:indexPath.row];
[cell.contentView addSubview:addbutton];
[addbutton addTarget:self action:#selector(addclicked:) forControlEvents:UIControlEventTouchUpInside];
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(350.0, 60.0, 50.0, 25.0)];
[label setBackgroundColor:[UIColor whiteColor]];
label.text=#"2.99$";
label.font = [UIFont boldSystemFontOfSize:18];
[cell.contentView addSubview:label];
[label release];
[cell.contentView addSubview:lab];
return cell;
}
-(IBAction)detailSubView:(id)sender{
NSLog(#"working in detail view");
UIButton *button = (UIButton *)sender;
NSLog(#"%d",button.tag);
a=button.tag;
NSLog(#"%d",a);
category1* B2 = [[category1 alloc] init];
UINavigationController *B2Nav = [[UINavigationController alloc] initWithRootViewController:B2];
B2Nav.modalTransitionStyle = UIModalTransitionStyleFlipHorizontal;
[self presentModalViewController:B2Nav animated:YES];
[B2 release];
[B2Nav release];
}
-(IBAction)addclicked:(id)sender{
UIButton *button = (UIButton *)sender;
NSLog(#"%d",button.tag);
a=button.tag;
}