开发者

How can I get scrollViewDidScrollToTop to work in a UITableView?

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:(UI开发者_StackOverflowScrollView *)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?


What happens if you try this?

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    if (scrollView.contentOffset.y == 0)
        NSLog(@"At the top");
}


- (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?


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.


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.


Do it in Swift:

func scrollViewDidScroll(scrollView: UIScrollView) {
    print(scrollView.contentOffset.y) 
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜