Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iPhone: How to allow multiple selection in tabelview for a custom cell?

Tags:

ios

iphone

ios4

How can I adapt this to be able to make multiple selections? and get the selected ones

- (id)initWithCellIdentifier:(NSString *)cellID {
if ((self = [super initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellID])) {

    UITableViewCell *cell=self; 
            UIImage *cry = [UIImage APP_CRYSTAL_SELECT];
    self.leftImage = [[[UIImageView alloc] initWithImage:cry] autorelease] ;
            [self.contentView addSubview:leftImage];            
}

And the selected method is:

- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
    [super setSelected:selected animated:animated];
      if(selected)
      {
       NSArray *subviews=[self.contentView subviews];
        for(UIView* view in subviews){
          if([view isEqual:self.leftImage]){
             [self.leftImage setHighlightedImage:[UIImage APP_CRYSTAL_SELECTED]];
        }
    }
}
else
{       
    NSArray *subviews=[self.contentView subviews];
    for(UIView* view in subviews){
        if([view isEqual:self.leftImage]){
            [self.leftImage setHighlightedImage:[UIImage APP_CRYSTAL_SELECT]];
        }
    }
  }
}
like image 918
Spring Avatar asked Dec 04 '22 20:12

Spring


1 Answers

For multiple selection, setup an NSMutableArray ivar (selectedIndexPaths in this case) to hold the items that are selected. In didSelectRowAtIndexPath add or remove indexPaths to this array.

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{   
        if(![self.selectedIndexPaths containsObject:indexPath])
            [self.selectedIndexPaths addObject:indexPath];
        else
            [self.selectedIndexPaths removeObject:indexPath];
}

Use selectedIndexPaths later to do whatever you wish! Cheers!

-Akshay

like image 152
Akshay Avatar answered Dec 07 '22 10:12

Akshay