检测到UIScrollview底部到达
我有一个UIScrollView与图像,当用户滚动到滚动视图的结尾,我想更新的内容。 这是我的代码来检测何时到达滚动视图的底部:
下面的代码在scrollViewDidScroll:
delegate中实现
CGFloat scrollViewHeight = imagesScrollView.bounds.size.height; CGFloat scrollContentSizeHeight = imagesScrollView.contentSize.height; CGFloat bottomInset = imagesScrollView.contentInset.bottom; CGFloat scrollViewBottomOffset = scrollContentSizeHeight + bottomInset - scrollViewHeight; if(imagesScrollView.contentOffset.y > scrollViewBottomOffset){ [imagesView addSubview:imagesBottomLoadingView]; [self downloadImages]; }
我的问题是,当用户滚动到底部,我的函数被调用了几次,但我只想调用一次。 我尝试用imagesScrollView.contentOffset.y == scrollViewBottomOffset,但它不起作用,并没有调用该函数
你有没有想过添加一个布尔值。 在第一次调用方法时更新它,也许当用户滚动回来时。
如果你想迅速检测到他们:
override func scrollViewDidScroll(scrollView: UIScrollView) { if (scrollView.contentOffset.y >= (scrollView.contentSize.height - scrollView.frame.size.height)) { //reach bottom } if (scrollView.contentOffset.y < 0){ //reach top } if (scrollView.contentOffset.y >= 0 && scrollView.contentOffset.y < (scrollView.contentSize.height - scrollView.frame.size.height)){ //not top and not bottom }}
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView { float bottomEdge = scrollView.contentOffset.y + scrollView.frame.size.height; if (bottomEdge >= scrollView.contentSize.height) { // we are at the end } }
实现scrollViewDidScroll:
并检查contentOffset
到达最后
有时你必须在条件中使用+1,因为contentSize.height会给你几个小数,所以如果你使用这个,你可以避免它…
override func scrollViewDidScroll(scrollView: UIScrollView) { if (scrollView.contentOffset.y + 1) >= (scrollView.contentSize.height - scrollView.frame.size.height) { //bottom reached } }