iosobjective-cuitableview

Tableview Image is not changed while selecting row of Tableview in iOS


enter image description hereMy requirement is to manage the tableview rows for select,Select All and Delete.deleting rows is worked correctly.but when I select the row the image is not changed.Please give me solution where did I made mistake.I added my code

ViewController.h

@interface ViewController : UIViewController<UITableViewDelegate>
{
    NSMutableArray *tableData;
    NSMutableSet *selectedRows;
    UIToolbar *actionToolbar;
    UIImageView *imgView;
    BOOL selected;
    UIBarButtonItem *actionButton,*selectAllButton,*deleteButton;
}
@property(nonatomic,retain)NSMutableSet *selectedRows;
@property(nonatomic,retain)IBOutlet UITableView *tableView;
- (BOOL)selected;
-(void)handleLongPress:(UILongPressGestureRecognizer *)gestureRecognizer;
- (NSIndexPath *)indexPathForCellController:(id)cellController;

ViewController.m

#import "ViewController.h"
#import "MultiSelectTableViewCell.h"
@interface ViewController ()

@end
const NSInteger SELECTION_INDICATOR_TAG = 54321;
const NSInteger TEXT_LABEL_TAG = 54322;
@implementation ViewController
@synthesize tableView,selectedRows;


- (void)viewDidLoad
{
    [super viewDidLoad];
    tableData=[[NSMutableArray alloc]init];
    [tableData addObject:@"Row1"];
     [tableData addObject:@"Row2"];
     [tableData addObject:@"Row3"];
     [tableData addObject:@"Row4"];
     [tableData addObject:@"Row5"];
     [tableData addObject:@"Row6"];
     [tableData addObject:@"Row7"];
     [tableData addObject:@"Row8"];
     [tableData addObject:@"Row9"];
     [tableData addObject:@"Row10"];


    selectedRows=[[NSMutableSet alloc]init];
    actionToolbar = [[UIToolbar alloc] initWithFrame:CGRectMake(0, 416, 320, 44)];
    actionButton =
    [[UIBarButtonItem alloc]
      initWithTitle:@"Submit"
      style:UIBarButtonItemStyleBordered
      target:self
      action:@selector(noAction:)];

    NSMutableArray *buttons = [[NSMutableArray alloc ]initWithCapacity:2];

    selectAllButton=[[UIBarButtonItem alloc]initWithTitle:@"Select All" style:UIBarButtonItemStyleBordered target:self action:@selector(selectAllrows:)];

    deleteButton=[[UIBarButtonItem alloc]initWithTitle:@"Delete" style:UIBarButtonItemStyleBordered target:self action:@selector(deleterows:)];

    [self.tableView setAllowsSelectionDuringEditing:YES];

    self.tableView.allowsMultipleSelection = YES;

    selected=NO;

    [buttons addObject:actionButton];
    [buttons addObject:selectAllButton];
    [buttons addObject:deleteButton];


    [actionToolbar setItems:buttons];

    [self.view addSubview:actionToolbar];

    UILongPressGestureRecognizer *lpgr = [[UILongPressGestureRecognizer alloc]
                                          initWithTarget:self action:@selector(handleLongPress:)];
    lpgr.minimumPressDuration = 2.0; //seconds
    lpgr.delegate = self;
    [self.tableView addGestureRecognizer:lpgr];
    // Do any additional setup after loading the view, typically from a nib.
}
-(void)handleLongPress:(UILongPressGestureRecognizer *)gestureRecognizer
{
    CGPoint p = [gestureRecognizer locationInView:self.tableView];

    NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:p];
    if (indexPath == nil)
        NSLog(@"long press on table view but not on a row");
    else
        NSLog(@"long press on table view at row %d", indexPath.row);}
- (void)noAction:(id)sender
{

}
- (void)deleterows:(id)sender
{
//    [self.tableView deleteRowsAtIndexPaths:arrayOfIndexPathsToDelete withRowAnimation:UITableViewRowAnimationTop];
    NSLog(@"select rows are::%@ %d",selectedRows,[selectedRows count]);

    NSArray *array=[selectedRows allObjects];
    NSLog(@"indexes are::%@",array);

    for (int i=0; i<[array count]; i++) {
        NSLog(@"------%@",[array objectAtIndex:i]);

        NSIndexPath *myIP = [NSIndexPath indexPathForRow:[[array objectAtIndex:i] intValue] inSection:0] ;
        [self tableView:self.tableView commitEditingStyle:UITableViewCellEditingStyleDelete forRowAtIndexPath:myIP];

    }


//    [self.tableView deleteRowsAtIndexPaths:array withRowAnimation:UITableViewRowAnimationTop];

}
- (void)tableView:(UITableView *)tableview commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if(editingStyle == UITableViewCellEditingStyleDelete) {
        //Delete the object from the friends array and the table.
        [tableData removeObjectAtIndex:indexPath.row];
        NSLog(@"------%@",[indexPath description]);
        [self.tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
    }
}
- (void)selectAllrows:(id)sender
{

}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}
-(void)viewDidAppear:(BOOL)animated

{
    [self.tableView setEditing:YES];
}
// Customize the number of rows in the table view.
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return [tableData count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *cellIdentifier = @"MultiSelectCellController";
    UITableViewCell *cell =
    [self.tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    UIImageView *indicator;
    UILabel *textLabel;
    if (!cell)
    {
        cell =
        [[MultiSelectTableViewCell alloc]
          initWithFrame:CGRectMake(0, 0, 320,self.tableView.rowHeight)
          reuseIdentifier:cellIdentifier];


        indicator = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"NotSelected.png"]];

        const NSInteger IMAGE_SIZE = 30;
        const NSInteger SIDE_PADDING = 5;

        indicator.tag = SELECTION_INDICATOR_TAG;
        indicator.frame =
        CGRectMake(-EDITING_HORIZONTAL_OFFSET + SIDE_PADDING, (0.5 *self.tableView.rowHeight) - (0.5 * IMAGE_SIZE), IMAGE_SIZE, IMAGE_SIZE);
        [cell.contentView addSubview:indicator];

        textLabel = [[UILabel alloc] initWithFrame:CGRectMake(SIDE_PADDING, 0, 320, self.tableView.rowHeight)];
        textLabel.tag = TEXT_LABEL_TAG;
        textLabel.textColor = [UIColor blackColor];
        textLabel.backgroundColor = [UIColor clearColor];
        textLabel.font = [UIFont boldSystemFontOfSize:[UIFont labelFontSize]];
        [cell.contentView addSubview:textLabel];

        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.backgroundView = [[UIView alloc] init];
    }
    else
    {
        indicator = (UIImageView *)[cell.contentView viewWithTag:SELECTION_INDICATOR_TAG];
        textLabel = (UILabel *)[cell.contentView viewWithTag:TEXT_LABEL_TAG];
    }

    textLabel.text = [tableData objectAtIndex:[indexPath row]];



    if (selected)
    {
        indicator.image = [UIImage imageNamed:@"IsSelected.png"];
        cell.backgroundView.backgroundColor = [UIColor colorWithRed:223.0/255.0 green:230.0/255.0 blue:250.0/255.0 alpha:1.0];
    }
    else
    {
        indicator.image = [UIImage imageNamed:@"NotSelected.png"];
        cell.backgroundView.backgroundColor = [UIColor whiteColor];
    }

    return cell;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 45;
}
- (BOOL)selected
{
    return selected;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (self.tableView.isEditing)
    {
        //selected = !selected;

        selected=[self selected];

        NSNumber *rowNsNum = [NSNumber numberWithUnsignedInt:indexPath.row];
        if ( [self.selectedRows containsObject:rowNsNum] )
            [self.selectedRows removeObject:rowNsNum];
        else
        {
            [self.selectedRows addObject:rowNsNum];
            NSLog(@"index is:::%@",rowNsNum);
        }

        [self.tableView performSelector:@selector(reloadData) withObject:nil afterDelay:0.2];

        UITableViewCell *cell =[self.tableView cellForRowAtIndexPath:[self indexPathForCellController:[tableData objectAtIndex:[indexPath row]]]];
//    [tableView cellForRowAtIndexPath:
//     [(RootViewController *)tableView.delegate
//      indexPathForCellController:self]];

    UIImageView *indicator = (UIImageView *)[cell.contentView viewWithTag:SELECTION_INDICATOR_TAG];
    if (selected)
    {

        indicator.image = [UIImage imageNamed:@"IsSelected.png"];
        cell.backgroundView.backgroundColor = [UIColor colorWithRed:223.0/255.0 green:230.0/255.0 blue:250.0/255.0 alpha:1.0];
         selected = !selected;
    }
    else
    {
        indicator.image = [UIImage imageNamed:@"NotSelected.png"];
        cell.backgroundView.backgroundColor = [UIColor whiteColor];
    }
    }


//
//    cell.imageView.image = imgView.image;
}

- (NSIndexPath *)indexPathForCellController:(id)cellController
{


     NSLog(@"cell controller is;::%@",cellController);
    NSInteger sectionIndex;
//  NSInteger sectionCount = [tableData count];
    for (sectionIndex = 0; sectionIndex < 1; sectionIndex++)
    {
        NSArray *section = tableData;
        NSInteger rowIndex;
         NSLog(@"section count is:::%d",[section count]);
        NSInteger rowCount = [section count];
        for (rowIndex = 0; rowIndex < rowCount; rowIndex++)
        {
            NSArray *row = [section objectAtIndex:rowIndex];
            NSLog(@"row is:::%@",row);
            if ([row isEqual:cellController])
            {
                 selected=YES;
                 NSLog(@"row index is::%d",rowIndex);
                return [NSIndexPath indexPathForRow:rowIndex inSection:sectionIndex];
            }
        }
    }

    return nil;
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end

MultiSelectTableViewCell.h

#import <UIKit/UIKit.h>

@interface MultiSelectTableViewCell : UITableViewCell
{

}

@end

extern const NSInteger EDITING_HORIZONTAL_OFFSET;

MultiSelectTableViewCell.m

#import "MultiSelectTableViewCell.h"

const NSInteger EDITING_HORIZONTAL_OFFSET = 30;

@implementation MultiSelectTableViewCell

//
// setEditing:animated:
//
// Refreshed the layout when editing is enabled/disabled.
//
- (void)setEditing:(BOOL)editing animated:(BOOL)animated
{
    [self setNeedsLayout];
}

//
// layoutSubviews
//
// When editing, displace everything rightwards to allow space for the
// selection indicator.
//
- (void)layoutSubviews
{
    [UIView beginAnimations:nil context:nil];
    [UIView setAnimationBeginsFromCurrentState:YES];

    [super layoutSubviews];

    if (((UITableView *)self.superview).isEditing)
    {
        CGRect contentFrame = self.contentView.frame;
        contentFrame.origin.x = 30;
        self.contentView.frame = contentFrame;
    }
    else
    {
        CGRect contentFrame = self.contentView.frame;
        contentFrame.origin.x = 30;
        self.contentView.frame = contentFrame;
    }

    [UIView commitAnimations];
}

@end

Solution

  • You didn't handle the tag BOOL selected properly. Try this one in didselect delegate method:

         UIImageView *indicator = (UIImageView *)[cell.contentView viewWithTag:SELECTION_INDICATOR_TAG];
            if (selected)
            {
        
                indicator.image = [UIImage imageNamed:@"NotSelected.png"];
                cell.backgroundView.backgroundColor = [UIColor colorWithRed:223.0/255.0 green:230.0/255.0 blue:250.0/255.0 alpha:1.0];
               
            }
            else
            {
                indicator.image = [UIImage imageNamed:@"Selected.png"];
                cell.backgroundView.backgroundColor = [UIColor whiteColor];
               
            }
     selected = !selected;
            }