UITableView Scrolls to Top on Cell Refresh

后端 未结 4 1891
佛祖请我去吃肉
佛祖请我去吃肉 2021-02-04 10:08

I have a UITableView with a cell that is dynamically sized to fit a UITextView inside it. Whenever a key is typed, the cell checks to see if the calculated height has increased,

4条回答
  •  半阙折子戏
    2021-02-04 10:27

    Wow, Josh Gafni's answer helped a lot; he deserves an upvote. My solution is based off his. This still feels like a hack, so if anyone still has a better way to do this, I'm still very interested to hear it.

    First I save the content offset, then I start the update.

    CGPoint offset = self.tableView.contentOffset;
    [self.tableView beginUpdates];
    [self.tableView endUpdates];
    

    This animates the cell's height change and adjusts all the frames to suit the constraints.

    Next I remove all animations from the tableView's layer, so the animation to the top stops. Then I reset the contentOffst to what it was before.

    [self.tableView.layer removeAllAnimations];
    [self.tableView setContentOffset:offset animated:NO];
    

    Finally, I let the tableView handle the animated scroll down so the bottom of the cell is right above the keyboard.

    [self.tableView scrollToRowAtIndexPath:CreateNoteCellIndexPath atScrollPosition:UITableViewScrollPositionBottom animated:YES];
    

    And voila, it works pretty well.

    fixed cell resize

提交回复
热议问题