Shaik Tamim Shaik Tamim - 4 months ago 14
iOS Question

how to show selected rows with check marks while updating the previously selected rows in UITableView in objective c

i tried like this...in cellForRowAtIndex()

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *SimpleTableViewIdentifier=@"SimpleTableViewIdentifier";

UITableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:SimpleTableViewIdentifier];

if (cell == nil)
{
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:SimpleTableViewIdentifier];
}
cell.selectionStyle = UITableViewCellSelectionStyleNone;
cell.textLabel.text=[hardDependencyAlldataArray objectAtIndex:indexPath.row];

return cell;
}


and added below lines of code in didSelectRowAtIndexPath..

UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
cell.accessoryType = UITableViewCellAccessoryCheckmark;
[tableView deselectRowAtIndexPath:indexPath animated:YES];


but,while updating the previous selected value,check mark is not showing onpreviously selected rows..any one can help in this issue..Thanks in advance.. :)

Answer

I think this is what you need to do. In your cellForRowAtIndexPath method, instead of assigning cell.selectionStyle = UITableViewCellSelectionStyleNone; for all cells, assign it to none only for those cells which are not selected

Change the didSelectRowAtIndexPath method to store the selected cell detail to an array

UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
cell.accessoryType = UITableViewCellAccessoryCheckmark;
[self.selectedCellArray addObject:[hardDependencyAlldataArray objectAtIndex:indexPath.row]];
[tableView deselectRowAtIndexPath:indexPath animated:YES];

Now change the cellForRowAtIndexPath method like this

- (UITableViewCell *)tableView:(UITableView *)tableView    cellForRowAtIndexPath:(NSIndexPath *)indexPath
  {
       static NSString *SimpleTableViewIdentifier=@"SimpleTableViewIdentifier";

      UITableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:SimpleTableViewIdentifier];

      if (cell == nil)
      {
         cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:SimpleTableViewIdentifier];
      }
      cell.textLabel.text=[hardDependencyAlldataArray objectAtIndex:indexPath.row];

      if (![self.selectedCellArray containsObject:[hardDependencyAlldataArray objectAtIndex:indexPath.row]])
      {
          cell.selectionStyle = UITableViewCellSelectionStyleNone;
      }
      else
      {
          cell.accessoryType = UITableViewCellAccessoryCheckmark;
      }
      return  cell;
}
Comments