简体   繁体   中英

How to stop UITableView scrolling to top after insert new row?

I have used accordian view in my app, While I insert new row in the UITableView , everything works good if the section is in visible area. But when we update lower section row, UITableView scrolls to top automatically. Whats the issue here? Can anyone help me to resolve this issue?

   [CATransaction begin];

    [CATransaction setCompletionBlock:^{
     NSLog(@"Completed");
    } 
    [self.tableView beginUpdates];
    [self.tableView insertRowsAtIndexPaths: indexPathsToInsert withRowAnimation: UITableViewRowAnimationAutomatic];
    [self.tableView deleteRowsAtIndexPaths:indexPathsToDelete withRowAnimation:UITableViewRowAnimationAutomatic];
    [self.tableView endUpdates];
    [CATransaction commit];

Any suggestion? I tried scrollToRowAtIndexPath , setContentOffSet .

Are you using autolayout to let the tableview calculate the cell height? If yes, you have to set the estimatedHeight closed to the actual height of cell asap. If you have different height for different cells:

func tableView(_ tableView: UITableView, estimatedHeightForRowAt
indexPath: IndexPath) -> CGFloat

"accordian tutorial" works because it uses fixed cell height.

I didn't try but here's a list of things you can try :

  • Setting self.tableView.scrollEnabled = NO before your update and self.tableView.scrollEnabled = YES right after
  • Not sure but you can try to set self.tableView.scrollsToTop = NO
  • Save current position of scrollView in a CGPoint , then right after your update call [self.tableView setContentOffset:previousPosition animated:NO]

Hope this helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM