问题
I think the title explains it all. I want to be notified when a user scrolls to the top of a tableview.
I've tried the following with no luck and even added a UIScrollViewDelegate to the .h file.
- (void)scrollViewDidScrollToTop:(UIScrollView *)scrollView{
NSLog(@"ScrolledToTop");
}
Thanks!
Edit: I can get it to call if I press the status bar. But not if I scroll to the top. Weird... could it have something to do with the tableview bouncing when it reaches the top?
回答1:
What happens if you try this?
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
if (scrollView.contentOffset.y == 0)
NSLog(@"At the top");
}
回答2:
- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
if (indexPath.row == 0 && indexPath.section == 0 ) {
NSLog(@"Showing top cell");
}
Is that close enough?
回答3:
The func scrollViewDidScroll(_ scrollView: UIScrollView) delegate method will do the trick but it gets called each time the scrollview moves a point. A less hyperactive alternative could be this:
func scrollViewWillEndDragging(scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint>){
if targetContentOffset.memory.y == 0.0 {
println("Reached the Top")
}
It lets the delegate know the scrollView will reach the top before it actually gets there, and because targetContentOffset is a pointer you can change its value to adjust where the scrollview finishes its scrolling animation.
回答4:
Two more options that might be simpler based on your situation are:
First, if you're trying to detect the result of an animation only, triggered either by animating contentOffset yourself or by making a call to UITableView scrollToRowAtIndexPath:, or UICollectionView scrollToItemAtIndexPath:, implement
-(void)scrollViewDidEndScrollingAnimation:(UIScrollView *)scrollView {
// You're now at the end of the scrolling animation
}
This will not not be called after a manual scroll with your finger, which may or may not be helpful sometimes.
Second, if you're trying to do something like infinite scrolling, where you refresh the list when you get to the top, or load another page of results when you get to the bottom, an easy way to do it is to just use make the call in your data source cellForRowAtIndexPath: which might save you the need to implement the delegate all together.
回答5:
Do it in Swift:
func scrollViewDidScroll(scrollView: UIScrollView) {
print(scrollView.contentOffset.y)
}
来源:https://stackoverflow.com/questions/2113791/how-can-i-get-scrollviewdidscrolltotop-to-work-in-a-uitableview