IOS UITableView scrolls to the specified location

  • 2020-12-18 01:56:04
  • OfStack

The method is simple:


- (void)scrollToRowAtIndexPath:(NSIndexPath *)indexPath atScrollPosition:(UITableViewScrollPosition)scrollPosition animated:(BOOL)animated

Some caveats:

If you need to get the cell and the height of tableview immediately after reloadData, or if you need to scroll tableview, then you may have problems executing the code directly after reloadData.

reloadDate does not wait for the tableview update to complete before returning, but returns immediately, then computes the table height, gets cell, and so on.

If the data in the table is very large and does not complete in 1 run loop cycle, then the operation requiring the tableview view data becomes problematic.

apple does not provide api of reloadData directly. To delay the program until the end of reloadData, you can do the following:

Method 1:


[self.tableView reloadData];
[self.tableView layoutIfNeeded];
// Refresh to complete 

Method 2:


[self.tableView reloadData];
dispatch_async(dispatch_get_main_queue(), ^{
// Refresh to complete 
});

reloadDate executes in the main queue column, and dispatch_get_main_queue waits for an opportunity until the main queue is free.

Similar functions:


- (void)scrollToRowAtIndexPath:(NSIndexPath *)indexPath atScrollPosition:(UITableViewScrollPosition)scrollPosition animated:(BOOL)animated;
- (void)scrollToNearestSelectedRowAtScrollPosition:(UITableViewScrollPosition)scrollPosition animated:(BOOL)animated;
- (void)setContentOffset:(CGPoint)contentOffset animated:(BOOL)animated; // animate at constant velocity to new offset
- (void)scrollRectToVisible:(CGRect)rect animated:(BOOL)animated;

When using [tableView reloadData]; You cannot use the above function directly later when refreshing data. reload


Related articles: