I have created a check box using the uiimageview and i have placed the checkbox into the uitableview cell like below
i want to get indexpath.row when i check the check box.
so i added the uiimageviiew inside the cell. so the didSelectRowAtIndexPath is gets called and gives me the indexpath.row.
but when the row is selected i want to show the detailed view.
now this runs me into trouble.
so can you people suggest me how to tackle my above problem.
when i check the checkbox i want to get the indexpath.row.
and when the row is selected i need to show the detailed view.
Thanks for your time and help
UPDATE 1 :
// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
profileName = [appDelegate.archivedItemsList objectAtIndex:indexPath.row];
if (cell == nil)
{
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:#"xc"] autorelease];
cb = [[UIButton alloc] initWithFrame:CGRectMake(5,10, unselectedImage.size.width, unselectedImage.size.height)];
[cb setImage:unselectedImage forState:UIControlStateNormal];
[cb setImage:selectedImage forState:UIControlStateSelected];
[cb addTarget:self action:#selector(buttonAction:) forControlEvents:UIControlEventTouchDown];
[cell.contentView addSubview:cb];
}
if ( tableView == myTableView )
{
titleLabel = [[UILabel alloc]initWithFrame:CGRectMake(60, 0, 150, 35)];
titleLabel.font = [UIFont boldSystemFontOfSize:13];
titleLabel.textColor = [UIColor blackColor];
[cell.contentView addSubview:titleLabel];
NSString *subjectData = [profileName.archive_subject stringByTrimmingCharactersInSet: [NSCharacterSet whitespaceAndNewlineCharacterSet]];
[titleLabel setText:[NSString stringWithFormat: #"%# ", subjectData]];
lblDescription = [[UILabel alloc]initWithFrame:CGRectMake(60, 30, 210, 30)];
lblDescription.numberOfLines = 2;
lblDescription.lineBreakMode = YES;
lblDescription.adjustsFontSizeToFitWidth = YES;
lblDescription.font = [UIFont systemFontOfSize:10];
lblDescription.textColor = [UIColor grayColor];
[cell.contentView addSubview:lblDescription];
NSString *CompanyName = [profileName.archive_content stringByTrimmingCharactersInSet: [NSCharacterSet whitespaceAndNewlineCharacterSet]];
[lblDescription setText:[NSString stringWithFormat: #"%# ", CompanyName]];
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
}
return cell;
}
Use a UIButton instead of UIImageView for your checkbox - this way you can add an action/method to it, where you can grab the indexPath, plus you can add different images for selected/unselected state which will eliminate all the confusing stuff happening in your code above:
So in your cellForRowAtIndexPath: method:
-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
...// Your existing code here
UIImage *unselectedCheckboxImage = [UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:#"unselectedImageName" ofType:#"imageType"]];
UIImage *selectedCheckboxImage = [UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:#"selectedImageName" ofType:#"imageType"]];
UIButton *cb = [[UIButton alloc] initWithFrame:CGRectMake(desiredX, desiredY, unselectedCheckboxImage.frame.size.width, unselectedCheckboxImage.frame.size.height)];
[cb setImage:unselectedCheckboxImage forState:UIControlStateNormal];
[cb setImage:selectedCheckboxImage forState:UIControlStateSelected];
[cb addTarget:self action:#selector(buttonAction:) forControlEvents:UIControlEventTouchDown];
[cell.contentView addSubview:cb];
[cb release];
}
And then for your button action method:
- (IBAction)buttonAction:(id)sender
{
if ([sender isKindOfClass:[UIButton class]])
{
UIButton *checkboxButton = (UIButton*)sender;
checkboxButton.selected = !checkboxButton.selected;
NSIndexPath *indexPath = [self.myTableView indexPathForCell:(UITableViewCell*)[[checkboxButton superview] superview]];
// Do whatever you like here
}
}
I think your logic is causing the problem in the didSelectRowAtIndexPath: method; make sure that's right. Besides, if you just want to use check mark for the cell I think it's better if you use UITableViewCellAccessoryCheckmark. This may give you a basic idea.
Related
I have seen some posts before, but didn't get the answer yet, thats why i am trying to post again in more effective manner. How can i use check-uncheck functionality in UITableView like below image.
This is table i want when i click on button of any cell, that buttons image will change, not on all cells.
For Check-Uncheck functionality only buttonClicked: method is not enough. You will have also put the condition in cellForRowAtIndexPath: method for which button is selected or which in unselected because cellForRowAtIndexPath: method will call each time when you will scroll your UITableView and cells will be refresh.
And i saw your previous question you're adding two buttons with two action not a good way just change the image of button for check-uncheck.
So here is what i do for this -
#import <UIKit/UIKit.h>
#interface ViewController : UIViewController<UITableViewDelegate, UITableViewDataSource>
{
IBOutlet UITableView *tblView;
NSMutableArray *arrayCheckUnchek; // Will handle which button is selected or which is unselected
NSMutableArray *cellDataArray; // this is your data array
}
#end
Now in ViewController.m class -
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
arrayCheckUnchek = [[NSMutableArray alloc]init];
//Assign your cell data array
cellDataArray = [[NSMutableArray alloc]initWithObjects:#"cell-1",#"cell-2",#"cell-3",#"cell-4",#"cell-5", nil];
// setting all unchecks initially
for(int i=0; i<[cellDataArray count]; i++)
{
[arrayCheckUnchek addObject:#"Uncheck"];
}
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
return [cellDataArray count];
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if(cell == nil)
{
cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
cell.textLabel.text = [cellDataArray objectAtIndex:indexPath.row];
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
[button setFrame:CGRectMake(270.0, 7.0, 30.0, 30.0)];
if([[arrayCheckUnchek objectAtIndex:indexPath.row] isEqualToString:#"Uncheck"])
[button setImage:[UIImage imageNamed:#"uncheck_icon"] forState:UIControlStateNormal];
else
[button setImage:[UIImage imageNamed:#"check_icon"] forState:UIControlStateNormal];
[button addTarget:self action:#selector(buttonClicked:) forControlEvents:UIControlEventTouchUpInside];
[cell.contentView addSubview:button];
return cell;
}
-(void)buttonClicked:(id)sender
{
//Getting the indexPath of cell of clicked button
CGPoint touchPoint = [sender convertPoint:CGPointZero toView:tblView];
NSIndexPath *indexPath = [tblView indexPathForRowAtPoint:touchPoint];
// No need to use tag sender will keep the reference of clicked button
UIButton *button = (UIButton *)sender;
//Checking the condition button is checked or unchecked.
//accordingly replace the array object and change the button image
if([[arrayCheckUnchek objectAtIndex:indexPath.row] isEqualToString:#"Uncheck"])
{
[button setImage:[UIImage imageNamed:#"check_icon"] forState:UIControlStateNormal];
[arrayCheckUnchek replaceObjectAtIndex:indexPath.row withObject:#"Check"];
}
else
{
[button setImage:[UIImage imageNamed:#"uncheck_icon"] forState:UIControlStateNormal];
[arrayCheckUnchek replaceObjectAtIndex:indexPath.row withObject:#"Uncheck"];
}
}
And finally it will look like -
Tags are useful with customised uitableviewcell designed in IB. If you create cells programmatically, you don't need tags. You use them only to find correct uiview to set properties.
Yes this is simple to set Tags while declaring the classes inside UITableViewCell and identify them using tags. I have posted some sample code for your reference. Am not sure it will solve your problem. You asked how to set tags and identify the classes using tags. So it will give you some basic idea about your question.
-(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];
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
cell.selectionStyle = UITableViewCellSelectionStyleNone;
label1 = [[UIView alloc] initWithFrame:CGRectMake(2, 20, 15, 15)];
label1.tag = 100;
label1.backgroundColor = [UIColor whiteColor];
label1.layer.cornerRadius = 5;
[cell.contentView addSubview: label1];
label2 = [[UILabel alloc] initWithFrame:CGRectMake(25, 2, 165, 23)];
label2.tag = 101;
label2.font = [UIFont boldSystemFontOfSize:15];
label2.backgroundColor = [UIColor clearColor];
[cell.contentView addSubview: label2];
label3 = [[UILabel alloc] initWithFrame:CGRectMake(190, 2, 90, 23)];
label3.tag = 102;
label3.font = [UIFont systemFontOfSize:14];
label3.textColor = [UIColor colorWithRed:0.14117670588235 green:0.435294117647059 blue:0.847058823529412 alpha:1];
label3.backgroundColor = [UIColor clearColor];
label3.textAlignment = UITextAlignmentRight;
[cell.contentView addSubview: label3];
}
label1 = (UILabel *) [cell.contentView viewWithTag:100];
NSString *string1 = [array1 objectAtIndex:indexPath.row];
label2 = (UILabel *) [cell.contentView viewWithTag:101];
NSString * string2 = [array2 objectAtIndex:indexPath.row];
label3 = (UILabel *) [cell.contentView viewWithTag:102];
NSString * string3 = [array3 objectAtIndex:indexPath.row];
return cell;
}
Please let me know this is useful or not. Otherwise we'll go to some other way.
Happy Coding. Thanks.
i agree with #VakulSaini because u can do this to handle which cell touch or swipe or what ever and this is an ex:
-(void)handleSwipLeft:(UISwipeGestureRecognizer *)gestureRecognizer
{
CGPoint Location = [gestureRecognizer locationInView:self.tableView];
NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:Location];
cell = [tableView cellForRowAtIndexPath:indexPath];
}
Use cellForRowAtIndexPath method of UITableView and in This method Add any component like (UITextField,UILabel ..... etc ) In your UITableViewCell by using [cell.contentView addSubview:YourComponentName]; and give each component to its tag by indexPath.row.
such like ,,,
YourComponentName.tag = indexPath.row;
I have a tableview where I am displaying my values from database in tableview cells. In this tableview cellforrowatindexpath, I have created a button with an image on it and set selector for it. So when I click on the button my selector is called and it changes my image to another image.
But the problem is it does not identifies the indexpath i.e. if 4 rows are present in the tableview and if I click on the first row button, its image should change but problem is 4th row action is performed and its image is changed because it does not get the proper indexpath of the image to change.
This is my cellforrowatindexpath code:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
NSString *CellIdentifier = [NSString stringWithFormat:#"Cell%d%d", indexPath.section, indexPath.row];
appDelegate = (StopSnoozeAppDelegate*)[[UIApplication sharedApplication]delegate];
cell =(TAlarmCell *) [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[TAlarmCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
mimageButton = [UIButton buttonWithType:UIButtonTypeCustom];
mimageButton.frame=CGRectMake(10, 20, 20, 20);
mimageButton.tag = 1;
onButtonView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, 30, 50)];
onButtonView.tag = 2;
onButtonView.image = [UIImage imageNamed:#"alarm_ON.png"];
[mimageButton setImage:onButtonView.image forState:UIControlStateNormal];
[cell.contentView addSubview:mimageButton];
[mimageButton addTarget:self action:#selector(changeMapType::) forControlEvents:UIControlEventTouchUpInside];
}
return cell;
}
This is my changemapType code
-(void)changeMapType:(NSIndexPath*)path1:(UIButton*)sender{
appDelegate.changeimagetype =!appDelegate.changeimagetype;
if(appDelegate.changeimagetype == YES)
{
onButtonView.image = [UIImage imageNamed:#"alarm_OF.png"];
[mimageButton setImage:onButtonView.image forState:UIControlStateNormal];
appDelegate.changeimagetype = YES;
}
else
{
onButtonView.image = [UIImage imageNamed:#"alarm_ON.png"];
[mimageButton setImage:onButtonView.image forState:UIControlStateNormal];
appDelegate.changeimagetype = NO;
}
}
Don't break table view cell reuse just to put a different tag on each button. If your cells are the same, use the same reuse identifier.
You can find out the index path of the sender like this, without any need to mess around with tags. It also works for multi section tables.
CGPoint hitPoint = [sender convertPoint:CGPointZero toView:self.tableView];
NSIndexPath *hitIndex = [self.tableView indexPathForRowAtPoint:hitPoint];
I don't think you can have additional arguments in an #selector like that. What you might have to do is subclass UIButton and add an NSIndexPath property (or even just an int) and in -(void)changeMapType:(MyCustomButton*)sender access the property there.
Also it seems you do not even use the index path in changeMapType so that will need to be changed as well.
EDIT: Is it the button image you are trying to change? In which case you don't need the index path at all, or a subclass. Just use [sender setImage:(UIImage *)image forState:(UIControlState)state].
Use yourTableView for getting the Index Path.. Try something like this.
- (void)buttonAction:(UIButton*)sender {
UITableViewCell *cell = (UITableViewCell*)button.superview;
NSIndexPath *indexPath = [yourTableView indexPathForCell:cell];
NSLog(#"%d",indexPath.row)
}
I think following code might help you..
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UIView *myCheckbox = [[UIView alloc] init];
UIButton *myBt1 = [[UIButton alloc] initWithFrame:CGRectMake(10, 10, 30, 30)];
if([appDelegate.changeimagetype == YES"]){
[myBt1 setBackgroundImage:[UIImage imageNamed:#"alarm_ON.png"] forState:UIControlStateNormal];
}
else {
[myBt1 setBackgroundImage:[UIImage imageNamed:#"alarm_OF.png"] forState:UIControlStateNormal];
}
[myBt1 addTarget:self action:#selector(btcheckbox:) forControlEvents:UIControlEventTouchDown];
[myBt1 setTag:indexPath.row];
[myCheckbox addSubview:myBt1];
[myBt1 release];
[myCheckbox release];
[cell addsubview:myview];
return cell;
}
-(void) btcheckbox:(id) sender
{
UIButton *currentButton = (UIButton *) sender;
if([[currentButton backgroundImageForState:UIControlStateNormal] isEqual:[UIImage imageNamed:#"alarm_OF.png"]])
{
appDelegate.changeimagetype = YES;
[currentButton setBackgroundImage:[UIImage imageNamed:#"alarm_ON.png"] forState:UIControlStateNormal];
}else if([[currentButton backgroundImageForState:UIControlStateNormal] isEqual:[UIImage imageNamed:#"alarm_ON.png"]])
{
appDelegate.changeimagetype = NO;
[currentButton setBackgroundImage:[UIImage imageNamed:#"alarm_OF.png"] forState:UIControlStateNormal];
}
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
NSString *CellIdentifier = [NSString stringWithFormat:#"Cell%d", indexPath.row];
appDelegate = (StopSnoozeAppDelegate*)[[UIApplication sharedApplication]delegate];
cell =(TAlarmCell *) [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[TAlarmCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
UIButton *mimageButton = [UIButton buttonWithType:UIButtonTypeCustom];
mimageButton.frame=CGRectMake(10, 20, 20, 20);
mimageButton.tag = indexPath.row;
//onButtonView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, 30, 50)];
//onButtonView.tag = 2;
// onButtonView.image = [UIImage imageNamed:#"alarm_ON.png"];
[mimageButton setImage:[UIImage imageNamed:#"alarm_ON.png"] forState:UIControlStateNormal];
mimageButton.selected = NO;
[cell.contentView addSubview:mimageButton];
[mimageButton addTarget:self action:#selector(changeMapType:) forControlEvents:UIControlEventTouchUpInside];
}
return cell;
}
-(void)changeMapType:(UIButton*)sender{
if(sender.selected == YES)
{
// onButtonView.image = [UIImage imageNamed:#"alarm_OF.png"];
[sender setImage:[UIImage imageNamed:#"alarm_ON.png"] forState:UIControlStateNormal];
sender.selected = NO;
}
else
{
//onButtonView.image = [UIImage imageNamed:#"alarm_ON.png"];
[sender setImage:[UIImage imageNamed:#"alarm_OF.png"] forState:UIControlStateNormal];
sender.selected = YES;
}
}
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.
I am a new Programmer of i phone
i have a little problem.... i wants pass two arguments on button click....
//---insert individual row into the table view---
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:[NSString stringWithFormat:#"Cell %i",indexPath.section]];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:[NSString stringWithFormat:#"Cell %i",indexPath.section]] autorelease];
}
cell.selectionStyle = UITableViewCellSelectionStyleNone;//my code.... change the color or selected cell
search_items *pro = [searchCount objectAtIndex:[indexPath row]];
NSString *string1=[[NSString alloc]init];
NSString *string2=[[NSString alloc]init];
/// i wants access these two strings on buttonClicked Method...(pass as a argument):)
string1=pro.s_showroomName;
string2=pro.s_productName;
UIButton* aButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
aButton.frame = CGRectMake(150, 15,150,40);
[aButton setTag:indexPath.row];
[aButton addTarget:self action:#selector(buttonClicked:) forControlEvents:UIControlEventTouchUpInside];
[cell.contentView addSubview:aButton];
UIImage *img = [UIImage imageNamed:#"image.png"];
[aButton setImage:img forState:UIControlStateNormal];
[aButton setTitle:#"View Details" forState:UIControlStateNormal];
[aButton addSubview:buttonLabel1];
NSString *filepath=[[NSBundle mainBundle]pathForResource:pro.s_image ofType:#"png"];
UIImage *image=[UIImage imageWithContentsOfFile:filepath];
cell.imageView.image=image;
return cell;
}
-(void)buttonClicked:(UIButton*)sender {
//int tag = sender.tag;
}
One simple method to access your cell from the button, in the button callback is to ask it for it's superview's superview:
-(void)buttonClicked:(UIButton*)sender {
//int tag = sender.tag;
UIView* contentView = [sender superview];
if ([[contentView superview] isKindOfClass:[UITableViewCell class]] == NO) {
NSLog(#"Unexpected view hierarchy");
return;
}
UITableViewCell* cell = (UITableViewCell*)[contentView superview];
}
You can also, based on the frame of the button, find out which cell it belongs to in the table view. You would need to convert the frame from the button to the table view (UIView has methods to do the conversion).
The default UITableViewCell objects have a textLabel and a detailTextLabel, in your cellForRowAtIndexPath method you can set their text like this:
cell.textLabel.text = #"Some text";
cell.detailTextLabel.text = #"Some detail text";
then you can access these properties in your callback, when you have obtained the cell.
I have a table containing images and buttons. Each button has a tag with a different number. All buttons execute the same method when clicked. I will use the button's tag on the method they run, to know which button was clicked.
The problem is that the button's tag being reported is wrong. I imagine that as the cells are being reused, something is interfering with the tag.
This is the code I am using to populate the table on the fly:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *MyIdentifier = #"MyIdentifier";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:MyIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault
reuseIdentifier:MyIdentifier] autorelease];
UIButton *buyButton = [[UIButton alloc] initWithFrame:CGRectMake( 220, 4, 100, 35)];
buyButton.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
buyButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentCenter;
[buyButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
buyButton.titleLabel.font = [UIFont boldSystemFontOfSize:14];
[buyButton setBackgroundImage:newImage forState:UIControlStateNormal];
[buyButton addTarget:self action:#selector(buyNow:) forControlEvents:UIControlEventTouchDown];
[buyButton setTag: 1]; // I have to do this, to locate the button a few lines below
[cell addSubview:buyButton];
[buyButton release];
}
imageU = [[[UIImage alloc]initWithContentsOfFile:[[NSBundle mainBundle]
pathForResource:[NSString stringWithFormat: #"table-pg%d",numberX]
ofType:#"jpg"]] autorelease];
cell.imageView.image = imageU;
UIButton * myButton = (UIButton *) [cell viewWithTag:1];
[myButton setTitle:NSLocalizedString(#"buyKey", #"") forState:UIControlStateNormal];
UIImage *newImage = [[[[UIImage alloc]initWithContentsOfFile:[[NSBundle mainBundle]
pathForResource: #"whiteButton" ofType:#"png"]] autorelease]
stretchableImageWithLeftCapWidth:12.0f topCapHeight:0.0f];
[buyButton setTag:indexPath.row]; // the button's tag is set here
return cell;
}
and this is the buyNow method...
- (void) buyNow:(id)sender {
int index = [sender tag];
NSLog(#"button clicked = %d", index);
}
the button being reported as the clicked one cycles from 0 to 6, no number beyond 6 is ever reported. I think this corresponds to the cells being reused, why the number is not changing, is a mystery.
How to solve that?
thanks for any help.
Try moving the code that creates and sets up the button and adds it to the cell to the willDisplayCell method:
- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
I think this will allow you to reuse cells and also have a unique instance of the button in each one.