Can you animate a height change on a UITableViewCell when selected?

前端 未结 21 1382
天涯浪人
天涯浪人 2020-11-22 04:41

I\'m using a UITableView in my iPhone app, and I have a list of people that belong to a group. I would like it so that when the user clicks on a particular pers

21条回答
  •  时光说笑
    2020-11-22 04:59

    Add a property to keep track of the selected cell

    @property (nonatomic) int currentSelection;
    

    Set it to a sentinel value in (for example) viewDidLoad, to make sure that the UITableView starts in the 'normal' position

    - (void)viewDidLoad
    {
        [super viewDidLoad];
        // Do any additional setup after loading the view.
    
        //sentinel
        self.currentSelection = -1;
    }
    

    In heightForRowAtIndexPath you can set the height you want for the selected cell

    - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
        int rowHeight;
        if ([indexPath row] == self.currentSelection) {
            rowHeight = self.newCellHeight;
        } else rowHeight = 57.0f;
        return rowHeight;
    }
    

    In didSelectRowAtIndexPath you save the current selection and save a dynamic height, if required

    - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
            // do things with your cell here
    
            // set selection
            self.currentSelection = indexPath.row;
            // save height for full text label
            self.newCellHeight = cell.titleLbl.frame.size.height + cell.descriptionLbl.frame.size.height + 10;
    
            // animate
            [tableView beginUpdates];
            [tableView endUpdates];
        }
    }
    

    In didDeselectRowAtIndexPath set the selection index back to the sentinel value and animate the cell back to normal form

    - (void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(NSIndexPath *)indexPath {       
            // do things with your cell here
    
            // sentinel
            self.currentSelection = -1;
    
            // animate
            [tableView beginUpdates];
            [tableView endUpdates];
        }
    }
    

提交回复
热议问题