Only one UITableViewCellAccessoryCheckmark allowed at a time - iphone

I have a tableview with a section that contains a list of sounds the user can "pick." Only the currently selected sound should show a UITableViewCellAccessoryCheckmark. Basically I got it working. However, when e.g. the bottom cell is checked, and I scroll up the table view (making the checked cell go out of view), and I check another cell, the check for the bottom (out of view) cell is not removed. Does anyone know why this is?
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
static NSString *TheOtherOne = #"OtherCell";
static NSString *MiddleCell = #"MiddleCell";
// Configure the cell...
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
NSString *theSound = [prefs objectForKey:#"pickedFailSound"];
NSUInteger index = [failSounds indexOfObject:theSound];
if (indexPath.section == 0){
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
}
failAtLaunch = [[[UISwitch alloc] initWithFrame:CGRectMake(200, 7, 100, 30)] autorelease];
[cell addSubview:failAtLaunch];
cell.accessoryView = failAtLaunch;
cell.selectionStyle = UITableViewCellSelectionStyleNone;
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
if(![prefs boolForKey:#"failAtLaunch"]) {
[failAtLaunch setOn:NO animated:NO];
} else {
[failAtLaunch setOn:YES animated:NO];
}
[(UISwitch *)cell.accessoryView addTarget:self action:#selector(setIt) forControlEvents:UIControlEventValueChanged];
cell.textLabel.text = #"Instafail";
cell.detailTextLabel.text = #"Fail at Laucnh";
return cell;
} else if (indexPath.section == 1) {
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:MiddleCell];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:MiddleCell] autorelease];
}
NSString *cellTitle = [failSounds objectAtIndex:indexPath.row];
cell.textLabel.text = cellTitle;
if (indexPath.row == index) {
cell.accessoryType = UITableViewCellAccessoryCheckmark;
}
if ([cellTitle isEqualToString:#"Your Fail Sound"]){
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
if(![prefs boolForKey:#"customSoundAvailable"]) {
cell.selectionStyle = UITableViewCellSelectionStyleNone;
cell.userInteractionEnabled = NO;
cell.textLabel.textColor = [UIColor grayColor];
cell.detailTextLabel.text = #"Record a Custom Failsound First";
}
}
return cell;
} else {
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:TheOtherOne];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:TheOtherOne] autorelease];
}
cell.textLabel.text = #"Hold to record fail sound";
UIButton *btn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
btn.frame = CGRectMake(230.0f, 4.0f, 60.0f, 36.0f);
[btn setTitle:#"OK" forState:UIControlStateNormal];
[btn setTitle:#"OK" forState:UIControlStateSelected];
[btn addTarget:self action:#selector(recordAudio) forControlEvents:UIControlEventTouchDown];
[btn addTarget:self action:#selector(stop) forControlEvents:UIControlEventTouchUpInside];
[cell.contentView addSubview:btn];
return cell;
}
}
And:
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
[tableView deselectRowAtIndexPath:indexPath animated:YES];
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
NSString *theSound = [prefs objectForKey:#"pickedFailSound"];
NSUInteger index = [failSounds indexOfObject:theSound];
//NSLog(#"The index is: %#", index);
if (indexPath.section == 1){
NSIndexPath *oldIndexPath = [NSIndexPath indexPathForRow:index inSection:1];
NSLog(#"Oldindexpath is: %#", oldIndexPath);
UITableViewCell *newCell = [tableView cellForRowAtIndexPath:indexPath];
if (newCell.accessoryType == UITableViewCellAccessoryNone) {
newCell.accessoryType = UITableViewCellAccessoryCheckmark;
}
UITableViewCell *oldCell = [tableView cellForRowAtIndexPath:oldIndexPath];
if (oldCell != newCell){
if (oldCell.accessoryType == UITableViewCellAccessoryCheckmark) {
oldCell.accessoryType = UITableViewCellAccessoryNone;
}
}
NSString *pickedSound = [failSounds objectAtIndex:indexPath.row];
NSLog(#"Picked sound is %#", pickedSound);
[prefs setObject:pickedSound forKey:#"pickedFailSound"];
[prefs synchronize];
[self performSelector:#selector(loadSound) withObject:nil];
[failSound play];
}
}

You aren't remembering to reset the accessory type for dequeued cells.
This should fix it for you;
cell.accessoryType = UITableViewCellAccessoryNone;
if (indexPath.row == index) {
cell.accessoryType = UITableViewCellAccessoryCheckmark;
}
Handy tip : You may find it useful to use switch(indexPath.section) rather than lots of if ... elseif ... else constructs. Although you're OK now with just 2 sections, I find that using switch makes it easier to scale up the number of sections and also makes it mentally easier to read throught the code since you often have if .. else constructs used for other things - having the different syntax helps make it clearer what the tests are for.

In - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPathafter each declaration of cell try reseting the cells accessoryType by adding following line: cell.accessoryType = UITableViewCellAccessoryNone;

Related

Update label in UITableView

-(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];
}
// NSLog(#"msgcnt123 %#\n",[messageCount objectAtIndex:indexPath.row]);
NSArray *seperateArray = [[clist objectForKey:[[clist allKeys]objectAtIndex:indexPath.row]]componentsSeparatedByString:#"#"];
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
// NSLog(#"key %#\n",[[clist allKeys]objectAtIndex:indexPath.row]);
cell.textLabel.text = [seperateArray objectAtIndex:0];
// cell.textLabel.text = [contactlist objectAtIndex:indexPath.row];
cell.selectionStyle = UITableViewCellSelectionStyleNone;
// NSLog(#"sep %#\n",seperateArray);
if (![[seperateArray objectAtIndex:1] isEqualToString:#"0"]) {
NSLog(#"msgCount %#\n",[seperateArray objectAtIndex:1]);
lblCnt = [[UILabel alloc]initWithFrame:CGRectMake(260, 13, 20, 20)];
lblCnt.backgroundColor = [UIColor lightGrayColor];
lblCnt.textColor = [UIColor blackColor];
lblCnt.text = [seperateArray objectAtIndex:1];
lblCnt.textAlignment = UITextAlignmentCenter;
lblCnt.layer.masksToBounds = YES;
lblCnt.layer.cornerRadius = 2.0f;
[cell.contentView addSubview:lblCnt];
lblCnt.tag = 1000;
}
else
{
/*NSLog(#"msgCount1 %#\n",[seperateArray objectAtIndex:1]);
[lblCnt removeFromSuperview];
lblCnt.hidden = YES;*/
for (UIView *view in [cell.contentView subviews])
{
if (view.tag == 1000)
{
[view removeFromSuperview];
}
}
}
return cell;
}
I am displaying contact name with a label in UITableView.The label displaying number of received messages for each contact.My view name is chatViewcontroller.If I am in that view that label count does not updated.For ex:For contact name "John" label count is "2".When John receives a message that label count should be updated as "3".It is not happening so.It is updated if i move come from another view.Is it possible to Update tableView chatviewController itself?.
Make sure that you updated your datasource(clist) and then call [tableview reloadData]

UILabel does not disappear in UItableView

-(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];
}
// NSLog(#"msgcnt123 %#\n",[messageCount objectAtIndex:indexPath.row]);
NSArray *seperateArray = [[clist objectForKey:[[clist allKeys]objectAtIndex:indexPath.row]]componentsSeparatedByString:#"#"];
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
// NSLog(#"key %#\n",[[clist allKeys]objectAtIndex:indexPath.row]);
cell.textLabel.text = [seperateArray objectAtIndex:0];
// cell.textLabel.text = [contactlist objectAtIndex:indexPath.row];
cell.selectionStyle = UITableViewCellSelectionStyleNone;
// NSLog(#"sep %#\n",seperateArray);
if (![[seperateArray objectAtIndex:1] isEqualToString:#"0"]) {
NSLog(#"msgCount %#\n",[seperateArray objectAtIndex:1]);
lblCnt = [[UILabel alloc]initWithFrame:CGRectMake(260, 13, 20, 20)];
lblCnt.backgroundColor = [UIColor lightGrayColor];
lblCnt.textColor = [UIColor blackColor];
lblCnt.text = [seperateArray objectAtIndex:1];
lblCnt.textAlignment = UITextAlignmentCenter;
lblCnt.layer.masksToBounds = YES;
lblCnt.layer.cornerRadius = 2.0f;
[cell.contentView addSubview:lblCnt];
}
else
{
NSLog(#"msgCount1 %#\n",[seperateArray objectAtIndex:1]);
[lblCnt removeFromSuperview];
lblCnt.hidden = YES;
}
return cell;
}
I have added a label in each row which displays number of messages received.In didSelect method i make label count zero so i can disappear label from tableView.In case of more than one row in table view label not disappear.
The simple and dirty method to reach what u want is to use a tag
-(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];
}
NSArray *seperateArray = [[clist objectForKey:[[clist allKeys]objectAtIndex:indexPath.row]]componentsSeparatedByString:#"#"];
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
cell.textLabel.text = [seperateArray objectAtIndex:0];
cell.selectionStyle = UITableViewCellSelectionStyleNone;
if (![[seperateArray objectAtIndex:1] isEqualToString:#"0"]) {
lblCnt = [[UILabel alloc]initWithFrame:CGRectMake(260, 13, 20, 20)];
lblCnt.backgroundColor = [UIColor lightGrayColor];
lblCnt.textColor = [UIColor blackColor];
lblCnt.text = [seperateArray objectAtIndex:1];
lblCnt.textAlignment = UITextAlignmentCenter;
lblCnt.layer.masksToBounds = YES;
lblCnt.layer.cornerRadius = 2.0f;
[cell.contentView addSubview:lblCnt];
//Add a tag
lblCnt.tag = 1000;
}
else
{
/*
NSLog(#"msgCount1 %#\n",[seperateArray objectAtIndex:1]);
[lblCnt removeFromSuperview];
lblCnt.hidden = YES;
*/
for (UIView *view in [cell.contentView subviews]) {
if (view.tag == 1000) {
[view removeFromSuperview];
}
}
}
return cell;
}
and select the view based on the tag.

How can i dynamically change the UISwitch of UITableView?

I have a UItableView where every UITableViewCell is containing a UISwitch .Now my question is when i will click in one switch then how can i OFF other switches of the UITableViewCell
In my code i have already made the view and i can ON/OFF the switches.But i want to OFF all other switches except my selected switch.
Please some help me by giving an example or source code example.
With Best Regards
Edit
My 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] autorelease];
switchview = [[UISwitch alloc] initWithFrame:CGRectZero];
cell.accessoryView = switchview;
switchCondition = NO;
[switchview setOn:NO animated:YES];
[switchview addTarget:self action:#selector(updateSwitchAtIndexPath:) forControlEvents:UIControlEventValueChanged];
[switchview release];
}
if(switchCondition == YES){
[switchview setOn:YES animated:YES];
}
cell.selectionStyle = UITableViewCellSelectionStyleNone;
cell.contentView.backgroundColor = [UIColor clearColor];
cell.textLabel.text = [NSString stringWithFormat:#"%#",[cellValueArray objectAtIndex:indexPath.row]];
return cell;
}
- (void)updateSwitchAtIndexPath:(UISwitch*)sender {
if(sender.on){
switchCondition = YES;
[table reloadData];
}
}
Update your data model used by the table's data source, then reload the table (or at least the visible rows). This will cause each row to reload and each switch will get updated with the latest data.
Edit: Here's an updated version of your code:
You need an instance variable to track the state of each switch. Create an array to hold the YES and NO values. In the code below I will assume there is an instance variable named switchConditions of type NSMutableArray that has been setup with NSNumber objects representing the YES and NO values for each row. This is similar to your cellValueArray. You should also get rid of your switchView and switchCondition instance variables.
- (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.selectionStyle = UITableViewCellSelectionStyleNone;
UISwitchView *switch = [[UISwitch alloc] initWithFrame:CGRectZero];
cell.accessoryView = switch;
[switchview addTarget:self action:#selector(updateSwitchAtIndexPath:) forControlEvents:UIControlEventValueChanged];
[switch release];
}
UISwitchView *switch = (UISwitchView *)cell.accessoryView;
switch.tag = indexPath.row; // This only works if you can't insert or delete rows without a call to reloadData
BOOL switchState = [switchConditions[indexPath.row] boolValue];
switch.on = switchState; // this shouldn't be animated
cell.contentView.backgroundColor = [UIColor clearColor];
cell.textLabel.text = cellValueArray[indexPath.row];
return cell;
}
- (void)updateSwitchAtIndexPath:(UISwitch*)switch {
NSInteger row = switch.tag;
if (switch.on){
// This switch is on, turn all of the rest off
for (NSUInteger i = 0; i < switchConditions.count; i++) {
switchConditions[i] = #NO;
}
switchConditions[row] = #YES;
[self.tableView reloadData];
} else {
switchConditions[row] = #YES;
}
}

How to tell which rows toggle switch was changed

I have a tableview with the accessoryview of a toggle switch. I specify the section and the row and am having a difficult time determining which row was toggled. I used the toggleSwitch.tag to grab the indexRow but as my indexRow is part of an indexPath.section I am not sure how to tell which row I toggled.
Here is the code:
- (UITableViewCell *)tableAlert:(SBTableAlert *)tableAlert cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell;
Category *cat = [allCategories objectAtIndex:indexPath.section];
Subject *sub = [cat.subjects objectAtIndex:indexPath.row];
cell = [[[SBTableAlertCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:nil] autorelease];
UISwitch *toggleSwitch = [[UISwitch alloc] init];
cell.accessoryView = [[UIView alloc] initWithFrame:toggleSwitch.frame];
[cell.accessoryView addSubview:toggleSwitch];
cell.textLabel.text =sub.title;
cell.detailTextLabel.text = sub.category_title;
if (sub.active==1){
[toggleSwitch setOn:YES];
} else {
[toggleSwitch setOn:NO];
}
toggleSwitch.tag = indexPath.row;
[toggleSwitch addTarget:self action:#selector(viewButtonPushed:) forControlEvents:UIControlEventValueChanged];
[toggleSwitch release];
return cell;
}
- (void)viewButtonPushed:(id)sender {
UIButton *button = (UIButton *)sender;
UITableViewCell *cell = button.superview; // adjust according to your UITableViewCell-subclass' view hierarchy
NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
Category *cat = [allCategories objectAtIndex:indexPath.section];
Subject *sub = [cat.subjects objectAtIndex:indexPath.row];
selectedSubject = sub;
UISwitch* switchControl = sender;
NSLog( #"The switch is %#", switchControl.on ? #"ON" : #"OFF" );
if(switchControl.on){
[sub setActive:1];
NSLog(#"%# is being set to ACTIVE", selectedSubject.title);
}else{
[sub setActive:0];
NSLog(#"%# is being set to INACTIVE", selectedSubject.title);
}
[sub setIsDirty:YES];
[cat.subjects replaceObjectAtIndex:indexPath.row withObject:sub];
[sub autorelease];
[cat autorelease];
}
Here is my didSelectRowAtIndexPath. Do I need to have any reference to the toggleSwitch here?
- (void)tableAlert:(SBTableAlert *)tableAlert didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
Category *cat = [allCategories objectAtIndex:indexPath.section];
Subject *sub = [cat.subjects objectAtIndex:indexPath.row];
selectedSubject = sub;
NSLog(#"selectedSubject = %#", selectedSubject.title);
if (tableAlert.type == SBTableAlertTypeMultipleSelct) {
UITableViewCell *cell = [tableAlert.tableView cellForRowAtIndexPath:indexPath];
if (cell.accessoryType == UITableViewCellAccessoryNone)
[cell setAccessoryType:UITableViewCellAccessoryCheckmark];
else
[cell setAccessoryType:UITableViewCellAccessoryNone];
[tableAlert.tableView deselectRowAtIndexPath:indexPath animated:YES];
}
}
I have found that you need to go to the superview of the superview of the item in the cell (assuming that the button or control is right off the root of the cell) in order to get the pointer to the cell.
Try this instead:
UITableViewCell *cell = button.superview.superview;
and see if the results are any better. Check out my blog post on this for more information:
Two superviews are better than one

Iphone: Checkmarks in UITableview get mixed up when scrolling

I have a bit of a problem where my check marks that i apply to my rows in my UITableView get all mixed up when i scroll. Im pretty sure this has to do with how the iphone reuses the cells and when i scroll away from on that has a check mark it probably puts it back in when i gets a chance.
Could someone please give me some tips on how I might avoid this or possibly take a look at my methods and see if anything looks off?
I was thinking that maybe I could save each row selection that the user made and then check to see which rows were being displayed to make sure the correct ones got the checkmark but I could'nt see a way to do so.
Thanks so much.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"Cell";
CustomCell *cell = (CustomCell*)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[CustomCell alloc] initWithFrame:CGRectZero reuseIdentifier:CellIdentifier] autorelease];
[cell setAccessoryView:nil];
}
NSMutableArray *temp = [[NSMutableArray alloc]init];
for (int j = 0; j < [listOfRowersAtPractice count]; j++) {
if ([[differentTeams objectAtIndex:indexPath.section] isEqualToString:[[rowersAndInfo objectForKey:[listOfRowersAtPractice objectAtIndex:j]]objectForKey:#"Team"]]) {
[temp addObject:[listOfRowersAtPractice objectAtIndex:j]];
}
}
[cell.cellText setText:[temp objectAtIndex:indexPath.row]];
[temp removeAllObjects];
[temp release];
// Set up the cell...
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
[tableView deselectRowAtIndexPath:indexPath animated:YES];
UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
if (cell.accessoryType != UITableViewCellAccessoryCheckmark) {
cell.accessoryType = UITableViewCellAccessoryCheckmark;
}else {
cell.accessoryType = UITableViewCellAccessoryNone;
}
}
Yes save the state of the row which is selected and in cellforrowatindexpath after you get the cell reset it to default state and check the state of the row and change the state.
EDIT:
You can create a NSMutabaleArray with number of items equal to the number of items in your datasource which is the name temp in your code.
On select you can actually change the value at that index to some text like #"selected" in the above created array.
In your cellforrowatindexpath you can check this text if its selected or unselected and then change the property of the cell. Its like maintaining a bitmap state for selected and unselected states.
Give this a go :
static NSString *CellIdentifier = [NSString stringWithFormat:#"Cell %d",indexPath.row];
I had the same problem on one of my app's.
As for the check marks, are you using a core data store at all?
If you are use the following....
- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
NSManagedObject *item = [[self fetchedResultsController] objectAtIndexPath:indexPath];
if ([[item valueForKey:#"checks"] boolValue]) {
cell.accessoryType = UITableViewCellAccessoryCheckmark;
[cell.textLabel setTextColor:[UIColor redColor]];
[cell.detailTextLabel setTextColor:[UIColor redColor]];
} else {
cell.accessoryType = UITableViewCellAccessoryNone;
[cell.textLabel setTextColor:[UIColor blackColor]];
[cell.detailTextLabel setTextColor:[UIColor blackColor]];
}
}
And......
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
NSManagedObject *selectedObject = [self.fetchedResultsController objectAtIndexPath:indexPath];
if ([[selectedObject valueForKey:#"checks"] boolValue]) {
[selectedObject setValue:[NSNumber numberWithBool:NO] forKey:#"checks"];
} else {
[selectedObject setValue:[NSNumber numberWithBool:YES] forKey:#"checks"];
}
[managedObjectContext save:nil];
}
You need to reset/clear all settings in the cell whenever you reuse the cell.
So here, right after you get the cell,
you need to do something like
CustomCell *cell = (CustomCell*)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[CustomCell alloc] initWithFrame:CGRectZero reuseIdentifier:CellIdentifier] autorelease];
[cell setAccessoryView:nil];
}
cell.accessoryType = UITableViewCellAccessoryNone // This and other such calls to clean up the cell
You need refresh the accessoryType of cell, because the cell is reused then it inherited the accessoryType from a reused Cell, this is the solution:
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"cellIdentifier";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
//Refresh acessory for cell when tableview have many cells and reuse identifier
if([self.tableView.indexPathsForSelectedRows containsObject:indexPath]){
cell.accessoryType = UITableViewCellAccessoryCheckmark;
}else{
cell.accessoryType = UITableViewCellAccessoryNone;
}
cell.textLabel.text = #"Your text cell";
return cell;
}
it worked for me..
in cell for row at index path i had created a checkbox button..
after everytym tableview is scrolled cellForRowAtIndexPath Method gets called
hence i had to add condition in cellForRowAtIndexPath to check whether a cell has a checked or unchecked button
static NSString *simpleTableIdentifier = #"SimpleTableCell";
SimpleTableCell *cell = (SimpleTableCell *)[tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier];
if (cell == nil)
{
NSArray *nib = [[NSBundle mainBundle] loadNibNamed:#"SimpleTableCell" owner:self options:nil];
cell = [nib objectAtIndex:0];
}
cell.nameLabel.text = [tableData objectAtIndex:indexPath.row];
cell.thumbnailImageView.image = [UIImage imageNamed:[thumbnails objectAtIndex:indexPath.row]];
cell.prepTimeLabel.text = [prepTime objectAtIndex:indexPath.row];
checkbox = [[UIButton alloc]initWithFrame:CGRectMake(290, 5, 20, 20)];
[checkbox setBackgroundImage:[UIImage imageNamed:#"checkbox_empty.png"]
forState:UIControlStateNormal];
[checkbox addTarget:self action:#selector(checkUncheck:) forControlEvents:UIControlEventTouchUpInside];
[cell addSubview:checkbox];
if(selectedRows.count !=0)
{
if([[selectedRows objectAtIndex:indexPath.row]integerValue]==1)
{
[checkbox setImage:[UIImage imageNamed: #"checkbox_full.png"] forState:UIControlStateNormal];
}
else
{
[checkbox setImage:[UIImage imageNamed: #"checkbox_empty.png"] forState:UIControlStateNormal];
}
}
return cell;
}
method to define selection of checkbox is as
- (IBAction)checkUncheck:(id)sender {
UIButton *tappedButton = (UIButton*)sender;
NSLog(#"%d",tappedButton.tag);
if ([[sender superview] isKindOfClass:[UITableViewCell class]]) {
UITableViewCell *containerCell = (UITableViewCell *)[sender superview];
NSIndexPath *cellIndexPath = [self.tableView indexPathForCell:containerCell];
int cellIndex = cellIndexPath.row;
NSLog(#"cell index%d",cellIndex);
[selectedRows insertObject:[NSNumber numberWithInt:1] atIndex:cellIndex];
}
NSLog(#"%#",selectedRows);
if([tappedButton.currentImage isEqual:[UIImage imageNamed:#"checkbox_empty.png"]])
{
[sender setImage:[UIImage imageNamed: #"checkbox_full.png"] forState:UIControlStateNormal];
}
else
{
[sender setImage:[UIImage imageNamed: #"checkbox_empty.png"] forState:UIControlStateNormal];
}
}
do not forget to initialize selectedRows array..
happy coding...!!!