jeremy gv
jeremy gv

Reputation: 87

Multiple selection with multiple sections in UItableview

If I select the first indexPath of first section , all the first indexPath of different sections gets selected like the image. How to rectify it?

enter image description here

if ([arraySelectedValue‌​s containsObject:array‌​StateNames[indexPath.‌​row]]) { 
    cell.imageCheck.imag‌​e =[UIImage imageNamed:@"check"]‌​; 
} else { 
    cell.imageCheck.imag‌​e =[UIImage imageNamed:@"uncheck‌​"];
}

Upvotes: 0

Views: 351

Answers (2)

Crazy Developer
Crazy Developer

Reputation: 3464

For this you need create a global arr to hold selected indexPath in your h file

NSMutable *arrSelectedIndex;

in your didSelectItemAtIndexPath you need to write below code.

-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    [self selectDeselectIndexpath:indexPath];
    [collectionView reloadData];

}


// this method is used to toggle between selection and deselection 
-(void) selectDeselectIndexpath : (NSIndexPath *) indexPath{

    for (int i=0; i < arrSelectedIndex.count; i++) {
        NSIndexPath *index = [arrSelectedIndex objectAtIndex:i];
        if (index.row == indexPath.row && index.section == indexPath.section) {
            [arrSelectedIndex removeObject:index];
            return ;
        }
    }
    [arrSelectedIndex addObject:indexPath];

}
// this method is used to select any indexPath
-(void) selectIndexpath : (NSIndexPath *) indexPath{

    for (int i=0; i < arrSelectedIndex.count; i++) {
        NSIndexPath *index = [arrSelectedIndex objectAtIndex:i];
        if (index.row == indexPath.row && index.section == indexPath.section) {
            return ; // This means indexPath already selected
        }
    }
    [arrSelectedIndex addObject:indexPath];
}
    // this method is used to deselect any indexPath
-(void) deselectIndexpath : (NSIndexPath *) indexPath{

    for (int i=0; i < arrSelectedIndex.count; i++) {
        NSIndexPath *index = [arrSelectedIndex objectAtIndex:i];
        if (index.row == indexPath.row && index.section == indexPath.section) {
            [arrSelectedIndex removeObject:index];
            return ; // Indexpath found and remove from array
        }
    }
    // Reaching over here means this indexpath not selected;
}

You can use any the above method as per you need.

Upvotes: 0

Deepak Kumar
Deepak Kumar

Reputation: 175

Change your code to the following.

if ([arraySelectedValue‌​s containsObject:indexPath])
{
    cell.imageCheck.imag‌​e =[UIImage imageNamed:@"check"]‌​;
}
else
{
    cell.imageCheck.imag‌​e =[UIImage imageNamed:@"uncheck‌​"];

}

and in didSelectRow method write the below code

if ([arraySelectedValues containsObject:indexPath])
{
    [arraySelectedValues removeObject:indexPath];
}
else
{
    [arraySelectedValues addObject:indexPath];

}

and reload the section or row

Upvotes: 1

Related Questions