Is there any way to find out which UITableViewCell
is at the top of the scroll window?
I'd like to get the current scroll position so that I can save it when the app exits. When the app gets started I want to scroll to the position it was at when it last exited.
To scroll to the top of our tableview we need to create a new IndexPath . This index path has two arguments, row and section . All we want to do is scroll to the top of the table view, therefore we pass 0 for the row argument and 0 for the section argument. UITableView has the scrollToRow method built in.
UITableView scrolls back because it's content size is equal to it's frame (or near to it). If you want to scroll it without returning you need add more cells: table view content size will be large then it's frame.
You can add a UITableView to a UIScrollView and have it scroll horizontally.
Since a scrollView has a panGesture we can check the velocity of that gesture. If the tableView was programmatically scrolled the velocity in both x and y directions is 0.0. By checking this velocity we can determine if the user scrolled the tableView because the panGesture has a velocity.
Scrolling to the top of a UITableView can be a useful feature depending on the type of app that you are making. If you have a tableview with hundreds of cells it can be annoying scrolling to the top of the tableview once you have scrolled far down the tableview.
Table views are more versatile than you might think. For example, many developers make their life harder using a scroll view when a UITableView would be a better choice. Finally, architecture is crucial for table views.
When the user scrolls back to a row, the table view will request its data again. The tableView(_:numberOfRowsInSection:) method tells the table view how many elements a section contains. The table view uses this information to prepare its scrolling area and display a scroll bar of the appropriate size.
Were you using a UITableViewController? One of the few things it does is call reloadData () on the table view. Now you have to do it yourself. Place it after you assign the data source to the table view.
You can easily grab the exact offset of the table view by looking at its contentOffset
property. For the vertical scroll, look at:
tableView.contentOffset.y;
The accepted solution only works if you know the size of all table view items. With auto sizing/estimated size that is not always true.
One alternative is to save the first visible item and scroll to it.
You can get the first visible item indexPath with:
savedIndex = tableView.indexPathsForVisibleRows?.first
Then scroll to it by doing:
tableView.scrollToRowAtIndexPath(savedIndex, atScrollPosition: .Top, animated: false)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With