UITableView scroll down

I have this line of code:

tableView.contentOffset = CGPointMake(0.0f, 10000000.0f); 

The content size is much smaller than 10000000.0f , but the UITableView still does not scroll down. How can i do this?

+7
source share
4 answers

Scrolling to tableViewCell ?

 //for instance, you have 15 cells NSIndexPath *indexPath = [NSIndexPath indexPathForRow:14 inSection:0]; [self.tableView scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionTop animated:YES]; 
+13
source

You can create a UITableView extension and use it wherever you need it as a regular table view method.

 extension UITableView { let SCREEN_HEIGHT = UIScreen.mainScreen().bounds.height func scrollToBottom(animated: Bool) { var y: CGFloat = 0.0 if self.contentSize.height > SCREEN_HEIGHT { y = self.contentSize.height - SCREEN_HEIGHT } self.setContentOffset(CGPointMake(0, y), animated: animated) } } 

Whenever the size of the content is greater than the height of the screen, it will scroll according to the correct position. This method also works with AutoLayout.

+2
source

try this code:

 self.tableView.reloadData() DispatchQueue.main.asyncAfter(deadline: DispatchTime.now()+0.1, execute: { let indexPath = IndexPath(row: self.dateSource.count-1, section: 0) self.tableView.scrollToRow(at: indexPath, at: UITableViewScrollPosition.bottom, animated: true) }) 
0
source

Swift 5, iOS 12 tested

Code This code works fine for a UITableView , even if there are sections with 0 elements (which will crash in any other solution I have seen on the Internet)

 extension UITableView { func scrollTableViewToBottom(animated: Bool) { guard let dataSource = dataSource else { return } var lastSectionWithAtLeasOneElements = (dataSource.numberOfSections?(in: self) ?? 1) - 1 while dataSource.tableView(self, numberOfRowsInSection: lastSectionWithAtLeasOneElements) < 1 { lastSectionWithAtLeasOneElements -= 1 } let lastRow = dataSource.tableView(self, numberOfRowsInSection: lastSectionWithAtLeasOneElements) - 1 guard lastSectionWithAtLeasOneElements > -1 && lastRow > -1 else { return } let bottomIndex = IndexPath(item: lastRow, section: lastSectionWithAtLeasOneElements) scrollToRow(at: bottomIndex, at: .bottom, animated: animated) } } 

Code This code works for UIScrollView , but will not work for UITableView , which has more cells than one screen can accommodate, due to the strange internal implementation of Apple's UITableViewController :

 extension UIScrollView { func scrollToBottom(animated: Bool) { guard contentSize.height > bounds.size.height else { return } let bottomOffset = CGPoint(x: 0, y: contentSize.height - bounds.size.height + contentInset.bottom) setContentOffset(bottomOffset, animated: true) } } 
0
source

Source: https://habr.com/ru/post/974257/


All Articles