Analyzer warning in Facebook API for iOS - iphone

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...

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

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

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;

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.

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

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 {
}