How to animate UITableViewCell height using auto-layout?

前端 未结 2 1457
旧时难觅i
旧时难觅i 2020-12-08 08:21

There are lot of similar questions on Stack Overflow about UITableViewCell height animation, but nothing works for new iOS8 auto-layout driven table view. My is

2条回答
  •  死守一世寂寞
    2020-12-08 08:25

    The following worked for me:

    Preparation:

    1. On viewDidLoad tell the table view to use self-sizing cells:

      tableView.rowHeight = UITableViewAutomaticDimension;
      tableView.estimatedRowHeight = 44; // Some average height of your cells
      
    2. Add the constraints as you normally would, but add them to the cell's contentView!

    Animate height changes:

    Say you change a constraint's constant:

    myConstraint.constant = newValue;
    

    ...or you add/remove constraints.

    To animate this change, proceed as follows:

    1. Tell the contentView to animate the change:

      [UIView animateWithDuration: 0.3 animations: ^{ [cell.contentView layoutIfNeeded] }]; // Or self.contentView if you're doing this from your own cell subclass
      
    2. Then tell the table view to react to the height change with an animation

      [tableView beginUpdates];
      [tableView endUpdates];
      

    The duration of 0.3 on the first step is what seems to be the duration UITableView uses for its animations when calling begin/endUpdates.

    Bonus - change height without animation and without reloading the entire table:

    If you want to do the same thing as above, but without an animation, then do this instead:

    [cell.contentView layoutIfNeeded];
    [UIView setAnimationsEnabled: FALSE];
    [tableView beginUpdates];
    [tableView endUpdates];
    [UIView setAnimationsEnabled: TRUE];
    

    Summary:

    // Height changing code here:
    // ...
    
    if (animate) {
        [UIView animateWithDuration: 0.3 animations: ^{ [cell.contentView layoutIfNeeded]; }];
        [tableView beginUpdates];
        [tableView endUpdates];
    }
    else {
        [cell.contentView layoutIfNeeded];
        [UIView setAnimationsEnabled: FALSE];
        [tableView beginUpdates];
        [tableView endUpdates];
        [UIView setAnimationsEnabled: TRUE];
    }
    

    You can check out my implementation of a cell that expands when the user selects it here (pure Swift & pure autolayout - truly the way of the future).

提交回复
热议问题