When Scrolling a table view cell out of view, cell text changes - iphone

I have a UITableView and i programatically add two buttons to the cell. 1 button adds to the cells text ( counts up ) the other subtracts 1 (counts down). However, lets say i add 4, the cell's text will be 4, but when i scroll that cell up and out of the view, when it comes back down into view, the cells text is back to 1 which is where it started out. The same happens if i add(it does the same if i subtract also) to the cells text and switch pages and then go back to the table view. Here is the cellForRow:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath: (NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil)
{
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
newBtn = [[UIButton alloc]init];
newBtn=[UIButton buttonWithType:UIButtonTypeRoundedRect];
[newBtn setFrame:CGRectMake(260,20,55,35)];
[newBtn addTarget:self action:#selector(subtractLabelText:) forControlEvents:UIControlEventTouchUpInside];
[newBtn setTitle:#"-" forState:UIControlStateNormal];
[newBtn setEnabled:YES];
[cell addSubview:newBtn];
subBtn = [[UIButton alloc]init];
subBtn=[UIButton buttonWithType:UIButtonTypeRoundedRect];
[subBtn setFrame:CGRectMake(200,20,55,35)];
[subBtn addTarget:self action:#selector(addLabelText:) forControlEvents:UIControlEventTouchUpInside];
[subBtn setTitle:#"+" forState:UIControlStateNormal];
[subBtn setEnabled:YES];
[cell addSubview:subBtn];
}
[cell setSelectionStyle:UITableViewCellSelectionStyleNone];
cell.imageView.image = [imageArray objectAtIndex:indexPath.row];
cell.textLabel.text = [cells objectAtIndex:indexPath.row];
return cell;
}
Any and all help is appreciated! Thanks:D
Methods for buttons
- (IBAction)addLabelText:(id)sender{
cell = (UITableViewCell*)[sender superview];
cell.textLabel.text = [NSString stringWithFormat:#"%d",[cell.textLabel.text intValue] +1];
}
- (IBAction)subtractLabelText:(id)sender
{
cell = (UITableViewCell*)[sender superview];
if ( [[cell.textLabel text] intValue] == 0){
cell.textLabel.text = [NSString stringWithFormat:#"%d",[cell.textLabel.text intValue] +0];
}
else{
cell.textLabel.text = [NSString stringWithFormat:#"%d",[cell.textLabel.text intValue] -1];
//[myTableView reloadData];
}
}

You need something like this, where you are storing the values outside the cells. This is because the cells get reused and are not good long term storage.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath: (NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil)
{
subBtn = [[UIButton alloc]init];
subBtn=[UIButton buttonWithType:UIButtonTypeRoundedRect];
[subBtn setFrame:CGRectMake(200,20,55,35)];
[subBtn addTarget:self action:#selector(addLabelText:indexPath.row) forControlEvents:UIControlEventTouchUpInside];
[subBtn setTitle:#"+" forState:UIControlStateNormal];
[subBtn setEnabled:YES];
[cell addSubview:subBtn];
}
// we're loading the value from the array each time the cell is displayed.
cell.textLabel.text = [cellLabelValues objectAtIndex:indexPath.row];
return cell;
}
- (IBAction)addLabelText:(int)currentRow{
NSString *newValue = [NSString stringWithFormat:#"%d",[[[cellLabelValues objectAtIndex:currentRow] intValue] +1];
// we update the value in the array since this is the source of the data for the cell
[cellLabelValues replaceObjectAtIndex:currentRow withObject:newValue];
// now reload to get the new value
[myTableView reloadData];
}

Related

adding text field in table view on button click

I have a table view and in each row there is a add button on click the new row adding below i want that onclick the row has one text field in it and a user can enter a texh on it can you help me how to add a text field in the adding row.
here is my code
-(void)buttonclicked:(UIButton *)sender
{
UIButton *btn = (UIButton *)[self.view viewWithTag:sender.tag];
NSLog(#"clickedCell=%i", btn.tag);
[[NSUserDefaults standardUserDefaults]setValue:[NSString stringWithFormat:#"%i", btn.tag] forKey:#"btntag"];
[self.choices insertObject:#"newrow" atIndex:btn.tag+1];
[self.tableView reloadData];
}
and the table view method
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil)
{
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
UIButton *button = [UIButton buttonWithType:UIButtonTypeContactAdd];
button.tag = indexPath.row;
button.frame = CGRectMake(280.0, 10, 25, 30.0); // x,y,width,height
[button addTarget:self action:#selector(buttonclicked:) forControlEvents:UIControlEventTouchUpInside];
[cell addSubview:button];
UILongPressGestureRecognizer *longPress = [[UILongPressGestureRecognizer alloc] initWithTarget:cell action:nil];
longPress.delegate = self;
[cell addGestureRecognizer:longPress];
int count = 0;
if(self.editing && indexPath.row != 0)
count = 1;
NSLog([NSString stringWithFormat:#"%i,%i",indexPath.row,(indexPath.row-count)]);
// Set up the cell...
if(indexPath.row == ([_choices count]) && self.editing)
{
cell.textLabel.text = #"ADD";
return cell;
}
NSString *choice = [self.choices objectAtIndex:indexPath.row];
cell.textLabel.text = choice;
return cell;
}
try like this may be it helps to you,
1.take one global variable type integer for example position.
2.when you click on particular button -(void)buttonclicked:(UIButton *)sender method will call in this method you will assign the btn.tag value to the position .
3.after that you are reloading the table view in the tableview cellForRowAtIndexPath method take one condition like
if(position==indexpath.row)
{
//add your textfield here
}.

How to show buttons in uitableview cell and their action will be shown on label on the same cell

In UITableViewCell there are different buttons and when I click on any button its action is being performed on all the cells, but I want that when I press the button then the action will be shown on the label of the same cell, I know I need to put them in array but how...?
when I click on the button one value is being incremented and it should be shown on the label of the same cell
here is the code:-
-(UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
cell=[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
likeShow=[[UILabel alloc]initWithFrame:CGRectMake(0, 160, 80, 20)];
likeBtn=[UIButton buttonWithType:UIButtonTypeCustom];
[likeBtn addTarget:self action:#selector(likeFn) forControlEvents:UIControlEventTouchUpInside];
likeBtn.frame=CGRectMake(0, 110, 90, 50);
[likeBtn setTitle:#"Like" forState:UIControlStateNormal];
[likeBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
[cell addSubview:likeBtn];
[cell addSubview:likeShow];
return cell;
}
This is the action of the button
-(void)likeFn{
NSString *str;
NSMutableString *mystring=[NSMutableString string];
likeCount++;
str =[NSString stringWithFormat:#"%d",likeCount];
NSString *world = #"Like";
NSString *helloWorld = [world stringByAppendingString:str];
likeShow.text=helloWorld;
}
Try the below code
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
NSString *CellIdentifier = [NSString stringWithFormat:#"Cell-%d",indexPath.row];
UITableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil)
{
cell=[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
//[cell clearsContextBeforeDrawing];
}
cell.selectionStyle = UITableViewCellSelectionStyleNone;
int lbltag = 1000;
UIButton *likeBtn = nil;
UILabel *likeShow = nil;
if ([cell viewWithTag:lbltag])
{
likeShow = (UILabel*)[cell viewWithTag:lbltag];
}
else
{
likeShow=[[[UILabel alloc]initWithFrame:CGRectMake(0, 0, 80, 20)] autorelease];
likeShow.text = [NSString stringWithFormat:#"%d likes",[[_marrTest objectAtIndex:indexPath.row] intValue]];
likeShow.tag = lbltag;
[cell addSubview:likeShow];
}
if ([cell viewWithTag:indexPath.row+1])
{
likeBtn = (UIButton*)[cell viewWithTag:indexPath.row+1];
}
else
{
likeBtn=[UIButton buttonWithType:UIButtonTypeCustom];
likeBtn.tag = indexPath.row+1;
[likeBtn addTarget:self action:#selector(likeFn:) forControlEvents:UIControlEventTouchUpInside];
likeBtn.frame=CGRectMake(90, 0, 90, 50);
[likeBtn setTitle:#"Like" forState:UIControlStateNormal];
[likeBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
[cell addSubview:likeBtn];
}
return cell;
}
-(void)likeFn:(UIButton*)btnClicked
{
NSString *strLikes = [_marrTest objectAtIndex:btnClicked.tag-1];
int likeCount = [strLikes intValue] + 1;
[_marrTest replaceObjectAtIndex:btnClicked.tag-1 withObject:[NSString stringWithFormat:#"%d",likeCount]];
NSIndexPath *selectedIndexPath = [NSIndexPath indexPathForRow:btnClicked.tag-1 inSection:0];
UITableViewCell *cell = [self.tableView cellForRowAtIndexPath:selectedIndexPath];
UILabel *requiredLabel = (UILabel*)[cell viewWithTag:1000];
NSString *str = requiredLabel.text;
//str = [str stringByAppendingFormat:#"selected %#", str];
requiredLabel.text = #"";
requiredLabel.text = [NSString stringWithFormat:#"%d likes",[[_marrTest objectAtIndex:btnClicked.tag-1] intValue]];
//do what ever you want with the label
}
Create cell in separate nib file. add button and label for for that cell.
Also create a view class for that cell and set class for cell in nib file as class you created. Make outlet form nib to class file. Also create action for button and implement action. and use that cell in your table view.
-(UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
cell=[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
likeShow=[[UILabel alloc]initWithFrame:CGRectMake(0, 160, 80, 20)];
likeBtn=[UIButton buttonWithType:UIButtonTypeCustom];
[likeBtn addTarget:self action:#selector(likeFn::) forControlEvents:UIControlEventTouchUpInside];
likeBtn.frame=CGRectMake(0, 110, 90, 50);
[likeBtn setTitle:#"Like" forState:UIControlStateNormal];
[likeBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
[cell.contentView addSubview:likeBtn];
[cell.contentView addSubview:likeShow];
return cell;
}
-(void)likeFn:(UIButton *)sender :(UIEvent *)event{
NSSet *touches = [event allTouches];
UITouch *touch = [touches anyObject];
CGPoint currentTouchPosition = [touch locationInView:self.view];
NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:currentTouchPosition];
UITableViewCell *cell = [self.tableView cellForRowAtIndexPath:indexPath];
NSString *str;
NSMutableString *mystring=[NSMutableString string];
likeCount++;
str =[NSString stringWithFormat:#"%d",likeCount];
NSString *world = #"Like";
NSString *helloWorld = [world stringByAppendingString:str];
for(id subView in cell.contentView.subviews){
{
if([subView isKindOfClass:[UILabel class]]){
UILabel *tmpLabel = (UILabel *)subView;
tmpLabel.text=helloWorld;
}
}
}
Try this code it may help you
try setting tags as:
likeBtn.tag = indexPath.row;
likeShow.tag = indexPath.row;
and in the likeFn:
- (void)likeFn: (id)sender {
UIButton * btn = (UIButton*)sender;
//check if the btn tag and label tag are same.
}
Check with this code.This may helpful for you.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
NSString *CellIdentifier = #"Cell";
UITableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil)
{
cell=[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
[cell clearsContextBeforeDrawing];
}
cell.selectionStyle = UITableViewCellSelectionStyleNone;
likeShow=[[UILabel alloc]initWithFrame:CGRectMake(0, 160, 80, 20)];
likeBtn=[UIButton buttonWithType:UIButtonTypeCustom];
[likeBtn addTarget:self action:#selector(likeFn) forControlEvents:UIControlEventTouchUpInside];
likeBtn.frame=CGRectMake(0, 110, 90, 50);
[likeBtn setTitle:#"Like" forState:UIControlStateNormal];
[likeBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
[cell addSubview:likeBtn];
[cell addSubview:likeShow];
return cell;
}
USE didSelectRowAtIndexPath method
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
return;
}

Scrolling of UITableview change the images of UIButton , UITableview scrolling issue

What i am doing is , I have an UITableview and i added UIButton as a custom view . I am giving tag to each button and tag got received in the action method. When i press the button it change the images for selected and unselected button but when i scroll it , it will come to normal state.
This is my cell for row at index method
static NSString *CellIdentifier = #"Cell4";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil)
{
cell = [self tableviewCellWithReuseIdentifierFollowing:CellIdentifier];
}
followingButton = [UIButton buttonWithType:UIButtonTypeCustom];
[followingButton addTarget:self action:#selector(followingButtonpressed:)forControlEvents:UIControlEventTouchUpInside];
[followingButton setImage:[UIImage imageNamed:#"following12.png"] forState:UIControlStateNormal];
followingButton.frame = CGRectMake(220.0 ,20.0, 100, 40.0);
[cell.contentView addSubview:followingButton];
NSLog(#"row--%d",indexPath.row);
followingButton.tag=indexPath.row;
NSLog(#"followingButton.tag--%d",followingButton.tag);
[self configureCellFollowing:cell forIndexPath:indexPath];
return cell;
}
==================
//Here is the action method
-(void)followingButtonpressed:(id)sender
{
NSLog(#"sender tag --%d",[sender tag]);
UIButton *btnPly = (UIButton *)sender;
if([btnPly isSelected])
{
[btnPly setSelected:NO];
[btnPly setImage:[UIImage imageNamed:#"following12.png"] forState:UIControlStateNormal];
}
else
{
[btnPly setSelected:YES];
[btnPly setImage:[UIImage imageNamed:#"following_off12.png"] forState:UIControlStateNormal];
}
}
Note : This code create cell for each row of data (Not reuse cell)
You need to change only as describe , May be helpful for you
NSString *CellIdentifier = [NSString stringWithFormat:#"S%1dR%1d",indexPath.section,indexPath.row];
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
may be solve your problem :)
The reason your buttons are "resetting" is because tableView:cellForRowAtIndexPath gets called multiple times (whenever a cell is about to be visible).
Each time this gets called you are reinitializing your button and resetting the image to following12.png (the default state). That's why when you scroll the buttons appear to reset.
You can't rely on the cell itself to preserve state because the cell will get reset every time. You need to move your state somewhere else (like in an array instance variable). Then when you have to configure a new cell in tableView:cellForRowAtIndexPath you can initialize it to the proper state (based on the array).
So create an NSMutableArray instance variable called myStateArray (or whatever) to store your button states, then your cellForRowAtIndexPath should look more like:
static NSString *CellIdentifier = #"Cell4";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil)
{
cell = [self tableviewCellWithReuseIdentifierFollowing:CellIdentifier];
}
followingButton = [UIButton buttonWithType:UIButtonTypeCustom];
[followingButton addTarget:self action:#selector(followingButtonpressed:)forControlEvents:UIControlEventTouchUpInside];
// -- Fetch the state from your array
BOOL buttonPressed = [[self.myStateArray objectAtIndex:indexPath.row] boolValue];
// -- Initialize the button state correctly
[followingButton setSelected:buttonPressed];
if (buttonPressed) {
[followingButton setImage:[UIImage imageNamed:#"following12.png"] forState:UIControlStateNormal];
} else {
[followingButton setImage:[UIImage imageNamed:#"following_off12.png"] forState:UIControlStateNormal];
}
followingButton.frame = CGRectMake(220.0 ,20.0, 100, 40.0);
[cell.contentView addSubview:followingButton];
NSLog(#"row--%d",indexPath.row);
followingButton.tag=indexPath.row;
NSLog(#"followingButton.tag--%d",followingButton.tag);
[self configureCellFollowing:cell forIndexPath:indexPath];
return cell;
}
Then in your button press make sure to save the state:
-(void)followingButtonpressed:(id)sender
{
// -- Save the state
[self.myStateArray insertObject:[NSNumber numberWithBool:[btnPly isSelected]] atIndex:[sender tag]];
NSLog(#"sender tag --%d",[sender tag]);
UIButton *btnPly = (UIButton *)sender;
if([btnPly isSelected])
{
[btnPly setSelected:NO];
[btnPly setImage:[UIImage imageNamed:#"following12.png"] forState:UIControlStateNormal];
}
else
{
[btnPly setSelected:YES];
[btnPly setImage:[UIImage imageNamed:#"following_off12.png"] forState:UIControlStateNormal];
}
}
As I understand from code you create UIButton every time when UITableView asks for cell. In both cases if you create a new cell or you use dequeued one. Then you create and add one more button every time over already created one. Move button creation to cell creation if So your cellForRowAtIndexPath method should looks like
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"Cell4";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil)
{
cell = [self tableviewCellWithReuseIdentifierFollowing:CellIdentifier];
followingButton = [UIButton buttonWithType:UIButtonTypeCustom];
[followingButton addTarget:self action:#selector(followingButtonpressed:)forControlEvents:UIControlEventTouchUpInside];
[followingButton setImage:[UIImage imageNamed:#"following12.png"] forState:UIControlStateNormal];
followingButton.frame = CGRectMake(220.0 ,20.0, 100, 40.0);
[cell.contentView addSubview:followingButton];
}
NSLog(#"row--%d",indexPath.row);
followingButton.tag=indexPath.row;
NSLog(#"followingButton.tag--%d",followingButton.tag);
[self configureCellFollowing:cell forIndexPath:indexPath];
return cell;
}
But this will not be competed solution of your problem. As you probably know UITableView uses "reusable" cells to decrease system memory usage. It uses only amount of cells as it necessary to show at the moment. So in table with 100 cells it will create actually about 10. And all of them wont store correct state of all amount pressed/unpressed buttons. To achieve correct behaviour you have to refuse using tags and use some model logic instead. Easiest way - NSMutableArray where you will store buttons states. In followingButtonpressed: method you will set proper object to YES/NO and in cellForRowAtIndexPath you will read this value.
Check code below
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"Cell4";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil)
{
cell = [self tableviewCellWithReuseIdentifierFollowing:CellIdentifier];
followingButton = [UIButton buttonWithType:UIButtonTypeCustom];
[followingButton addTarget:self action:#selector(followingButtonpressed:)forControlEvents:UIControlEventTouchUpInside];
[followingButton setImage:[UIImage imageNamed:#"following12.png"] forState:UIControlStateNormal];
followingButton.frame = CGRectMake(220.0 ,20.0, 100, 40.0);
[cell.contentView addSubview:followingButton];
BOOL isSelected = [[statesArray objectAtIndex:btnPly.tag] boolValue];
[self setState:isSelected forButton:followingButton];
}
NSLog(#"row--%d",indexPath.row);
followingButton.tag=indexPath.row;
NSLog(#"followingButton.tag--%d",followingButton.tag);
[self configureCellFollowing:cell forIndexPath:indexPath];
return cell;
}
-(void)followingButtonpressed:(id)sender
{
NSLog(#"sender tag --%d",[sender tag]);
UIButton *btnPly = (UIButton *)sender;
BOOL isSelected = [[statesArray objectAtIndex:btnPly.tag] boolValue];
[statesArray replaceObjectAtIndex:btnPly.tag withObject:[NSNumber numberWithBool:!isSelected]];
if(isSelected)
{
[self setState:NO forButton:btnPly];
}
else
{
[self setState:YES forButton:btnPly];
}
}
- (void) setState:(BOOL)state forButton:(UIButton *)button
{
if(state)
{
[button setSelected:NO];
[button setImage:[UIImage imageNamed:#"following12.png"] forState:UIControlStateNormal];
}
else
{
[button setSelected:YES];
[button setImage:[UIImage imageNamed:#"following_off12.png"] forState:UIControlStateNormal];
}
}
Where statesArray is
NSMutableArray *statesArray = [NSMutableArray new];
and you have to create and initialize it somewhere in you class. Count of objects in statesArray has to be the same as count of cells int tableView.
This is because every time when you are scrolling then this code calling
[followingButton setImage:[UIImage imageNamed:#"following12.png"] forState:UIControlStateNormal];
so check now
static NSString *CellIdentifier = #"Cell4";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil)
{
cell = [self tableviewCellWithReuseIdentifierFollowing:CellIdentifier];
followingButton = [UIButton buttonWithType:UIButtonTypeCustom];
[followingButton addTarget:self action:#selector(followingButtonpressed:)forControlEvents:UIControlEventTouchUpInside];
[followingButton setImage:[UIImage imageNamed:#"following12.png"] forState:UIControlStateNormal];
followingButton.frame = CGRectMake(220.0 ,20.0, 100, 40.0);
[cell.contentView addSubview:followingButton];
[self configureCellFollowing:cell forIndexPath:indexPath];
}
return cell;
}

How to save data of tableview cell

i am using custom checkbox buttons in my table view and want to save the selected cell's data to a mutable array.... can anyone help me... Thanks
create a mutable array to store your selected data, lets call it 'yourSeparatedData' , set the tag of your checkbox in cellForRowAtIndexPath and set onCheck: method as target. the code will look like this:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
NSString *CellIdentifier = #"setMe";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil)
{
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyle………
}
checkBox = [UIButton buttonWithType:UIButtonTypeRoundedRect];
checkBox.frame = CGRectMake(customizeMe);
if(yourSeparatedData && [yourSeparatedData indexOfObject:[yourTableViewDataSource objectAtIndex:indexPath.row]] != NSNotFound)
{
[checkBox setBackgroundImage:[UIImage imageNamed:#"check.png"] forState:UIControlStateNormal];
}
else {
[checkBox setBackgroundImage:[UIImage imageNamed:#"unCheck.png"] forState:UIControlStateNormal];
}
[checkBox addTarget:self action:#selector(onCheck:) forControlEvents:UIControlEventTouchUpInside];
[checkBox setTag:indexPath.row];
[cell addSubview:checkBox];
return cell;
}
-(void)onCheck:(id)sender {
if(yourSeparatedData && [yourSeparatedData indexOfObject:[yourTableViewDataSource objectAtIndex:[sender tag]]] != NSNotFound)
{
[sender setBackgroundImage:[UIImage imageNamed:#"unCheck.png"] forState:UIControlStateNormal];
[yourSeparatedData removeObject:[yourTableViewDataSource objectAtIndex:[sender tag]]];
}
else {
[sender setBackgroundImage:[UIImage imageNamed:#"check.png"] forState:UIControlStateNormal];
[yourSeparatedData addObject:[yourTableViewDataSource objectAtIndex:[sender tag]]];
}
[yourTableView reloadData];
}
this code is not tested, you are using checkbox so I assumed that you want to separate not just one data, at the end of the selection, you will have 'yourSeparatedData' with the objects picked from your tableView.
you can try custom action in UITableView cell for button prees,you can also use put a check box image and on click you can change the image as checked here is the code
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath: (NSIndexPath *)indexPath{
UITableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:#"identifire"];
cell=[[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:#"identifire"] autorelease];
cell.detailTextLabel.text=[id_Array objectAtIndex:indexPath.row];
cell.detailTextLabel.hidden=YES;
button = [UIButton buttonWithType:UIButtonTypeCustom];
NSString *path1 = [[NSBundle mainBundle] pathForResource:#"n_cross" ofType:#"png"];
UIImage *buttonImage1 = [[UIImage alloc] initWithContentsOfFile:path1];
[button setImage:buttonImage1 forState:UIControlStateNormal];
[button addTarget:self
action:#selector(customActionPressed:)
forControlEvents:UIControlEventTouchDown];
[button setTitle:#"Custom Action" forState:UIControlStateNormal];
button.frame = CGRectMake(245.0f, 20.0f, 40.0f, 40.0f);
[cell addSubview:button];
[buttonImage1 release];
CGRect imageFrame=CGRectMake(10,8,50,50);
self.cellimage=[[[UIImageView alloc] initWithFrame:imageFrame] autorelease];
self.cellimage.image=[imageIdArray objectAtIndex:indexPath.row];
[cell.contentView addSubview:self.cellimage];
return cell;
}
-(void)customActionPressed :(id)sender
{
//Get the superview from this button which will be our cell
UITableViewCell *owningCell = (UITableViewCell*)[sender superview];
NSIndexPath *cell = [_tableView indexPathForCell:owningCell];
NSString *uid=[id_Array objectAtIndex:cell.row];
[id_Array removeObjectAtIndex:cell.row];
[_tableView reloadData];
[self performSelectorInBackground:#selector(ignoreRequest:) withObject:uid];
}
here i have an id_Array and on selection of a cell i just remove the object at that index
You have to do this manually, there is no facility in a UITableView or UITableViewController t o do this automatically.
When user selects any cell then in didSelectRowAtIndexPath you can add selected object dynamically.
[someMutableArr addObject:[tableArr objectAtIndex:indexPath.row]];
Try this
- (void)onButtonClick {
int numberOfSections = [tableView numberOfSections];
for (int section = 0; section < numberOfSections; section++) {
int numberOfRows = [tableView numberOfRowsInSection:section];
for (int row = 0; row < numberOfRows; row++) {
NSIndexPath *indexPath = [NSIndexPath indexPathForRow:row inSection:section];
UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
if (cell.accessoryType == UITableViewCellAccessoryCheckmark) {
// Cell is selected
//here you can add that values into an array
} else {
// Cell is not selected
}
}
}
}

iphone: how to add checkboxes to a uitableviewcell?

I just can't seem figure out how to do this hopefully someone here can help me. In my tableview i want to add checkboxes to each cell and if you touch the checkbox a checkmark appears and a specific action is supposed to happen. but if you just touch the cell a different action is supposed to happen. Does anyone have an idea how to do this?? I started doing the following. But i think my approach creates memory leaks and i don't know how to perform an action only for the button that was pressed instead for all of them.....
It would be great if someone could help me out....
- (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];
}
NSArray *tempArray = [[exerciseNames objectAtIndex:indexPath.section] objectForKey:#"rowValues"];
UIButton *checkButton = [UIButton buttonWithType:UIButtonTypeCustom];
checkButton.tag = indexPath.row;
[checkButton setFrame:CGRectMake(10, 10, 23, 23)];
if (checkButtonPressed == YES) {
[checkButton setBackgroundImage:[[UIImage imageNamed:#"checked.png"] stretchableImageWithLeftCapWidth:10.0 topCapHeight:0.0] forState:UIControlStateNormal];
}
else {
[checkButton setBackgroundImage:[[UIImage imageNamed:#"unchecked.png"] stretchableImageWithLeftCapWidth:10.0 topCapHeight:0.0] forState:UIControlStateNormal];
}
[checkButton addTarget:self action:#selector(checkAction) forControlEvents:UIControlEventTouchUpInside];
[cell addSubview:checkButton];
cell.imageView.image = [UIImage imageNamed:#"unchecked.png"];
cell.textLabel.adjustsFontSizeToFitWidth = YES;
cell.textLabel.text = [NSString stringWithFormat:#"%# (%#)", [[tempArray objectAtIndex:indexPath.row] objectForKey:#"full"], [[tempArray objectAtIndex:indexPath.row] objectForKey:#"short"]];
// Set up the cell...
return cell;
}
- (UITableViewCell *)tableView:(UITableView *)tv cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = [tv dequeueReusableCellWithIdentifier:#"CellWithSwitch"];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:#"CellWithSwitch"] autorelease];
cell.selectionStyle = UITableViewCellSelectionStyleNone;
cell.textLabel.font = [UIFont systemFontOfSize:14];
cell.accessoryType = UITableViewCellAccessoryCheckmark;
}
cell.textLabel.text = #"Sound Effects";
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)path {
UITableViewCell *cell = [tableView cellForRowAtIndexPath:path];
if (cell.accessoryType == UITableViewCellAccessoryCheckmark) {
cell.accessoryType = UITableViewCellAccessoryNone;
} else {
cell.accessoryType = UITableViewCellAccessoryCheckmark;
}
}
I would try subclassing UITableViewCell and make each cell the target of the buttons action. That way when the button is pressed, the event will be handled by the cell object, not the table controller. If you don't like that, you could try using the tag your assigning to the button to make a distinction. To do that, make your button selector be
checkAction:(UIButton *)_btn {}
and when you add the target,
[checkButton addTarget:self action:#selector(checkAction:) forControlEvents:UIControlEventTouchUpInside];
(notice the : at the end of the #selector())
I haven't tried the second way, but I think it would work.
In Cocoa Touch, a UISwitch is the UI paradigm equivalent for a checkbox on a desktop UI.
Your checkAction handler can check which control called it, and only change that one control.