Search code examples
iosuitableviewexpandable-table

how to rotate image in expandable cell when clicked on cell in ios?


I'm making a UITableView with expandable/collapsible cells for an iOS app. In that app I want to display an arrow down image and when click on it the image will be an up arrow. Is this possible?

Here is my code

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (selectedIndex == indexPath.row)
    {
        selectedIndex = -1;
        [myContestTableView reloadRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
        return;
    }
    if (selectedIndex != -1)
    {
        NSIndexPath *prevPath = [NSIndexPath indexPathForRow:selectedIndex inSection:0];
        selectedIndex = indexPath.row;
        [myContestTableView reloadRowsAtIndexPaths:[NSArray arrayWithObject:prevPath] withRowAnimation:UITableViewRowAnimationFade];
    }
    selectedIndex = indexPath.row;
    [myContestTableView reloadRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
}

This is my image named "rotateImage". Please help me. Here is my expandable cell default image:

enter image description here

When the user click on a cell the image will be an up arrow and if the user click again on cell default image should display again.


Solution

  • If you're subclassing your UITableViewCell you can use: setSelected: animated:, add your configuration there.

    - (void)setSelected:(BOOL)selected animated:(BOOL)animated
    {
        [super setSelected:selected animated:animated];
    
        YOURIMAGEVIEW.transform = CGAffineTransformMakeRotation(selected ? M_PI : 0);
    
        // Configure the view for the selected state
    }
    

    if not, you simply use that inside -cellForRowAtIndexPath like:

    - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
    {
        ...
        YOURTABLECELL.yourImageView.tranform = CGAffineTransformMakeRotation((selectedIndex == indexPath.row) ? M_PI : 0);
        ...
    
        return tableCell;
    }