How to animate UITableViewCell height using auto-layout?

前端 未结 2 1456
旧时难觅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:47

    I would like to add a few points to Alex's answer.

    If you call beginUpdates and endUpdates inside cellForRowAtIndexPath or willDisplayCell, your app will crash. After animating your cell's increase, you might want it stay the same after scrolling to your tableView. You might also want that the rest of the cells keep their height the same. But remember that cells are reusable, so you might end up with other cells having increased height.

    As a result, you will have to set the constraint constant inside cellForRowAtIndexPath depending on the item it represents. But if you call layoutIfNeeded afterwards, it will display a warning with your constraints. My belief is that it attempts to generate the cell layout before its new height is computed.

    public func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    ...
        myConstraint.constant = itemForCell.value == "x" ? 50 : 20 // stop right here
        cell.layoutIfNeeded() <- don't do this or some of your constraints will break
        beginUpdates() <-- if you do this your app will crash
        endUpdates() <-- same here
    

提交回复
热议问题