Check Uncheck buttons in uitableview's cell - iphone

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;

Related

Button in UITableView is appearing twice in iPad Master View Controller

Created a UITableView programmatically, data in my tableview in iPad Master View Controller is loaded dynamically, i am putting a button in the last cell, but the button is showing up again in the tableview underneath the cell... First time when the code is executed, the button appears only once, but next time it shows up twice... Here is the code...
- (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];
}
if([_objects count] > 1)
{
if(indexPath.row == [_objects count])
{
UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
//set the position of the button
button.frame = CGRectMake(cell.frame.origin.x + 50, cell.frame.origin.y + 15, 225, 30);
[button setTitle:#"Hide me" forState:UIControlStateNormal];
[button addTarget:self action:#selector(customActionPressed) forControlEvents:UIControlEventTouchUpInside];
button.backgroundColor= [UIColor clearColor];
[cell.contentView addSubview:button];
}
else
{
cell.textLabel.textAlignment = NSTextAlignmentCenter;
cell.selectionStyle = UITableViewCellSelectionStyleBlue;
cell.textLabel.textColor = [UIColor colorWithRed:0/255.0 green:100.0/255.0 blue:220.0/255.0 alpha:1.0];
cell.textLabel.font = [UIFont fontWithName:#"Helvetica-Bold" size:13];
cell.textLabel.text = [_objects objectAtIndex:indexPath.row];
NSLog(#"%#", [_objects objectAtIndex:indexPath.row]);
}
}
return cell;
}
for ex:: here is a snapshot of the tableview (how can i put the image here???)
aaa
bbb
ccc
ddd
eee
UIButton
UIButton is appearing again here in the tableview
Here is the image link http://s10.postimg.org/fwarb2661/i_OS_Simulator_Screen_shot_28_Dec_2013_10_57_32_A.png
any help is appreciated, thanks in advance..
Please write bellow code :
if (cell)
{
cell =nil;
}
before creating your tableview cell
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
//write here
if (cell)
{
cell =nil;
}
//*
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
For set background image in cell plese use bellow code :-
UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(X, Y, 277, 58)];
imageView.backgroundColor = [UIColor clearColor];
imageView.opaque = NO;
imageView.image = [UIImage imageNamed:#"yourImage.png"];
cell.backgroundView = imageView;
Probably because your table view is using the same cell again.
Make sure you delete the button from the cell every time.
Would help to see your code so I can point to you exact location...
Try this:
(void)prepareForReuse {
[super prepareForReuse];
}
In the method set the button to nil or any other elements showing twice. The cell is being reused and you need to run prepareForReuse to empty the old cells.

changing the position of the detailtextlabel in the cell?

I have an Iphone application in which i am combining two arrays and displaying in the same table.the problem here is i was not able to change the position of the detailed textlabel in the cell.here is my code snippet `
- (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];
UIImageView* img = [[UIImageView alloc]initWithImage:[UIImage imageNamed:#"cell_with_arrow.png"]];
[cell setBackgroundView:img];
[img release];
}
if(newssarray==nil||[newssarray count]==0)
{
}
else
{
NSDictionary *dicttable=[newssarray objectAtIndex:indexPath.row];
head=[dicttable objectForKey:#"news"];
head1=[dicttable objectForKey:#"name"];
NSString *sub=[dicttable objectForKey:#"created"];
NSLog (#"%#",head);
[[cell viewWithTag:12] removeFromSuperview];
[[cell viewWithTag:13] removeFromSuperview];
[[cell viewWithTag:14] removeFromSuperview];
UIButton *shopLabel=[self buttonWithText:head andFrame:CGRectMake(49, 12, 250,5)] ;
shopLabel.tag=12;
//shopLabel.autoresizingMask=UIViewAutoresizingFlexibleRightMargin;
[shopLabel addTarget:self action:#selector(openRestaurantsList) forControlEvents:UIControlEventTouchUpInside];
UIButton *shopLabel1=[self buttonWithText:head1 andFrame:CGRectMake(49, 12, 250,5)] ;
shopLabel1.tag=14;
//shopLabel.autoresizingMask=UIViewAutoresizingFlexibleRightMargin;
[shopLabel1 addTarget:self action:#selector(openRestaurantsList) forControlEvents:UIControlEventTouchUpInside];
cell.detailTextLabel.frame = CGRectMake(49, 30, 150,5);
if(indexPath.row < [newsseperatearray count])
{
UIImage *cellImage = [UIImage imageNamed:#"news.png"];
cell.imageView.image = cellImage;
//NSStringEncoding encoding=NSASCIIStringEncoding;
cell.imageView.frame=CGRectMake(0,0,48,48);
cell.imageView.bounds=CGRectMake(0,0,48,48);
[cell.imageView setClipsToBounds:NO];
NSLog(#"%#",sub);
cell.detailTextLabel.text = sub;
cell.detailTextLabel.backgroundColor = [UIColor clearColor];
}
else
{
UIImage *cellImage = [UIImage imageNamed:#"menu_icon.png"];
cell.imageView.image = cellImage;
//NSStringEncoding encoding=NSASCIIStringEncoding;
cell.imageView.frame=CGRectMake(0,0,48,48);
cell.imageView.bounds=CGRectMake(0,0,48,48);
[cell.imageView setClipsToBounds:NO];
}
[cell addSubview:shopLabel];
[cell addSubview:shopLabel1];
// [cell addSubview:shopLabel2];
}
return cell;
}
`can anybody help me to achieve this?
Make a UITableViewCell subclass, keep that cell style as UITableViewCellStyleSubtitle, and override layoutSubviews in that subclass. You can then change the frame of detailTextLabel (just make sure to call the super implementation of layoutSubviews in your method).

Data lose On UITableViewCell When UITableView Scrolling?

I am trying to implement UITableview based application. In my tableView their is 10 Section and each section having one row.
I want implement each section have Different type of ContentView(1-8 same ContentView 9th section Different ContentView). I did this code For that.
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 10;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return 1;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier1 = #"Cell1";
static NSString *CellIdentifier2 = #"Cell2";
UITextField *textField;
UITextView *textView;
NSUInteger section=[indexPath section];
if(section == 9){
UITableViewCell *cell=[self.tableView cellForRowAtIndexPath:indexPath];
//UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier1];
if(cell==nil){
cell=[[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier1]autorelease];
textView=[[UITextView alloc]initWithFrame:CGRectMake(5, 5, 290, 110)];
[textView setBackgroundColor:[UIColor scrollViewTexturedBackgroundColor
]];
[textView setTag:([indexPath section]+100)];
[cell.contentView addSubview:textView];
}else{
textView=(UITextView*)[cell.contentView viewWithTag:([indexPath section]+100)];
}
return cell;
}else {
UITableViewCell *cell=[self.tableView cellForRowAtIndexPath:indexPath];
// UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier2];
if(cell==nil){
cell=[[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier2]autorelease];
textField=[[UITextField alloc]initWithFrame:CGRectMake(5, 5, 290, 50)];
[textField setBackgroundColor:[UIColor scrollViewTexturedBackgroundColor]];
[textField setTag:([indexPath section]+100)];
[cell.contentView addSubview:textField];
}else{
textField=(UITextField*)[cell.contentView viewWithTag:([indexPath section]+100)];
}
return cell;
}
return nil;
}
My problem are:
1. After type some thing in the UITextField/UITextView i am scrolling in the UITableView. that time all data in the UITableViewCell(UITextField/UITextView) was lose, except last cell data.
2. If i create cell
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
Instead of
UITableViewCell *cell=[self.tableView cellForRowAtIndexPath:indexPath];
Data will repeating . How can i over come this problem?
This line:
UITableViewCell *cell=[self.tableView cellForRowAtIndexPath:indexPath];
Should never appear in your data source cellForRowAtIndexPath method.
Apart from that, your code is OK, except that you are not setting the text field value anywhere. You need a model (such as an array of strings for the 10 textfield values). This model should be updated when the textfields are edited, and in your method above you copy the value back out of the model and into the textfield's text property:
textfield.text = [self.modelArray objectAtIndex:indexPath.section];
The table pools and reuses cells in an unpredictable fashion, so that subview of a cell that just scrolled off the bottom might reappear next at the top, or might be disposed of.
This is why you saw it partially work. The cell's subviews work okay until their cell gets reused or unloaded, then things move to the wrong place or data disappears.
The solution is that your table's datasource needs to hold onto it's own data. This is usually an array representing your model. Your case is a little unusual because you are using the text controls in your table as inputs, rather than display, which is more typical.
I suggest doing it like this:
// in #interface
#property (nonatomic, retain) NSMutableArray *sections;
// in #implementation
#synthesize sections=_sections;
// at some point before the view appears
self.sections = [NSMutableArray array];
for (int i=0; i<10; i++) {
UIControl *textControl;
if (i<9) {
textControl=[[UITextView alloc]initWithFrame:CGRectMake(5, 5, 290, 110)];
} else {
textControl=[[UITextField alloc]initWithFrame:CGRectMake(5, 5, 290, 50)];
}
[textControl setBackgroundColor:[UIColor scrollViewTexturedBackgroundColor]];
[textControl setTag:i+100];
[sections addObject:textControl];
[textControl release];
}
Now your cellForRowAtIndexPath is a little simpler:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier1 = #"Cell1";
static NSString *CellIdentifier2 = #"Cell2";
NSUInteger section=[indexPath section];
if(section == 9) {
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier1];
if(cell==nil) {
cell=[[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier1]autorelease];
}
} else {
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier2];
if(cell==nil) {
cell = [[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier2]autorelease];
}
}
// who knows what subview this cell has? it might not have one, or it might have the wrong one
// just clean it up to be certain
for (UIView *view in cell.subviews) {
[view removeFromSuperView];
}
// get the textControl we set up for _this_ section/cell
UIControl *textControl = [self.sections objectAtIndex:section];
// now we have a fresh cell and the right textControl. drop it in
[cell addSubview:textControl];
return cell;
}
hey the reason is you are doing this things when cell is nil ? but you are not writing any code when cell is not nil.
look at this example , in this example i am adding image view in tableview cell , hence you can add textviews or any other views like this
UITableViewCell *cell = (UITableViewCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
UIImageView *imgView;
if(cell == nil)
{
cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:CellIdentifier] autorelease];
imgView = [[UIImageView alloc] initWithFrame:CGRectMake(100,0,100,62)];
[imgView setImage:[UIImage imageNamed:#"img.png"]];
imgView.tag = 55;
[cell.contentView addSubview:imgView];
[imgView release];
}
else
{
imgView = (id)[cell.contentView viewWithTag:55];
}
so as showin here imgView = (id)[cell.contentView viewWithTag:55]; you have to give tag to you and write code showing above in else..
Let you try to make the cell labels and textviews by using following code. It works for me.
if (tagvalue ==3) {
static NSString *CellIdentifier = #"Cell3";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle
reuseIdentifier:CellIdentifier] autorelease];
}
lbl7 = [[UILabel alloc] init];
[lbl7 setFont:[UIFont boldSystemFontOfSize:20]];
[cell.contentView addSubview:lbl7];
lbl7.backgroundColor = [UIColor clearColor];
lbl7.frame = CGRectMake(120, 5, 0, 40);
lbl7.tag = 70;
[lbl7 release];
lbl8 = [[UILabel alloc] init];
[lbl8 setFont:[UIFont boldSystemFontOfSize:18]];
[cell.contentView addSubview:lbl8];
lbl8.backgroundColor = [UIColor clearColor];
lbl8.textColor = [UIColor grayColor];
lbl8.frame = CGRectMake(120, 50, 0, 40);
lbl8.tag = 80;
[lbl8 release];
lbl7 = (UILabel*)[cell.contentView viewWithTag:70];
lbl8 = (UILabel*)[cell.contentView viewWithTag:80];
lbl7.text = [[rowsarray objectAtIndex:row]objectForKey:#"name"];
lbl8.text = [[rowsarray objectAtIndex:row]objectForKey:#"flavour"];
[lbl7 sizeToFit];
[lbl8 sizeToFit];
return cell;
}
if (tagvalue ==4) {
static NSString *CellIdentifier = #"Cell4";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier] autorelease];
}
lbl9 = [[UILabel alloc] init];
[lbl9 setFont:[UIFont boldSystemFontOfSize:20]];
[cell.contentView addSubview:lbl9];
lbl9.backgroundColor = [UIColor clearColor];
lbl9.frame = CGRectMake(120, 5, 0, 40);
lbl9.tag = 90;
[lbl9 release];
lbl10 = [[UILabel alloc] init];
[lbl10 setFont:[UIFont boldSystemFontOfSize:18]];
[cell.contentView addSubview:lbl10];
lbl10.backgroundColor = [UIColor clearColor];
lbl10.textColor = [UIColor grayColor];
lbl10.frame = CGRectMake(120, 50, 0, 40);
lbl10.tag = 100;
[lbl10 release];
lbl9 = (UILabel*)[cell.contentView viewWithTag:90];
lbl10 = (UILabel*)[cell.contentView viewWithTag:100];
lbl9.text = [[rowsarray objectAtIndex:row]objectForKey:#"name"];
lbl10.text = [[rowsarray objectAtIndex:row]objectForKey:#"flavour"];
[lbl9 sizeToFit];
[lbl10 sizeToFit];
return cell;
}
I had same issue. Its not the problem with table class. The issue is at the place where you are calling this tableviewcontroller. First make the object of this call in .h and then allocate in .m, thats it..
When I was declaring in viewdidload like tbl *t = [self.storyboard...];, I was also facing the same problem. But when I put tbl *t; in .h problem solved.

pass two arguments on button clicked (access two strings on button click)

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.

Help me to get the IndexPath.row value

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.