简体   繁体   中英

Change button image on a cell when a tableView Cell is selected

I'm having a UITableView with the table view cell loaded from an .xib. Which has a label text and a checkmark button. I want to change the checkmark image of the button when the cell is selected. (Allows multiple selection). From these selected cells with changed checkmark image, i'm performing an operation.

Can anyone tell me how this could be done?

Thanks in advance....

Follow the below to change the button image.

Single Selection

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
    if (selectedIndex == indexPath.row) {
      // change image here...
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    selectedIndex = indexPath.row;
    [tableView reloadData];
}

If you need for multiple selection then you can maintain a array to capture the indexes and do the needful like below.

Multiple selection

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
   if ([selectedIndexArray containsObject:indexPath.row]) {
      // change image to check mark here...
   } else {
      // Change image to un-check mark
   }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if ([selectedIndexArray containsObject:indexPath.row]) {
       [selectedIndexArray removeObject:indexPath.row];
    } else {
       [selectedIndexArray addObject:indexPath.row];
    }
  [tableView reloadData];
}

You can have a field isCheckMarked in your model class, which you have then put in array for your tableview to populate. You can then toggle that flag in didSelectRow delegate of tableView and can change checkmark image based on isCheckMarked

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM