我试图实现这样一个检测滚动量的表视图,并决定显示导航栏或不显示。
@interface HomeViewController () {
NSInteger scrollAmount;
bool navbarHidden = NO;
}
@implementation HomeViewController
@synthesize lastContentOffset = _lastContentOffset;
bool navbarHidden = NO;
- (void)awakeFromNib
{
[super awakeFromNib];
scrollAmount = 0;
distance = 50;
}
-(void)scrollViewDidScroll:(UIScrollView *)scrollView {
CGPoint offset = scrollView.contentOffset;
CGRect bounds = scrollView.bounds;
UIEdgeInsets inset = scrollView.contentInset;
if (offset.y > self.lastContentOffset.y)
{
scrollAmount++;
}
else
{
scrollAmount--;
}
bool awayFromTop = offset.y > distance + inset.top;
if (awayFromTop && !navbarHidden) {
[[self navigationController] setNavigationBarHidden:YES animated:YES];
navbarHidden = YES;
} else if (!awayFromTop || (scrollAmount < -100)) {
[[self navigationController] setNavigationBarHidden:NO animated:YES];
navbarHidden = NO;
}
self.lastContentOffset = offset;
}
-(void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
scrollAmount = 0;
}
基本上,scrollViewDidScroll
计算滚动量,如果用户向上滚动,则会将scrollAmount
递减-1。
如果offset
足够接近屏幕顶部(!awayFromTop
)或滚动量小于-100,则预计导航栏会被隐藏。
当我为NSLog
程序运行scrollAmount
时,它正在隐藏导航。当用户离开顶部时显示栏,或者当接近顶部并且scrollAmount
正确打印时显示。
但只要scrollAmount
达到-100 [[self navigationController] setNavigationBarHidden:NO animated:YES];
未执行且不知何故scrollViewDidScroll
被无限调用,我就意味着程序进入无限循环。 scrollAmount
打印如-100,-101,-102 ......, - 1005 ......
然后我使用了以下代码:
if ([scrollView.panGestureRecognizer translationInView:self.view].y < heightOfScreen/-4.0f && !navbarHidden) {
[self.navigationController setNavigationBarHidden:YES animated:YES];
navbarHidden = YES;
} else if ([scrollView.panGestureRecognizer translationInView:self.view].y > heightOfScreen/4.0f && navbarHidden) {
[self.navigationController setNavigationBarHidden:NO animated:YES];
navbarHidden = NO;
}
显然[scrollView.panGestureRecognizer translationInView:self.view].y
给出了......类似于scrollAmount
,但它工作得很完美,现在我想知道为什么我的实现失败了。任何想法都赞赏。
答案 0 :(得分:0)
代码看起来正确,但如果我是你,我会使用
- (void)scrollViewWillEndDragging:(UIScrollView *)scrollView withVelocity:(CGPoint)velocity targetContentOffset:(inout CGPoint *)targetContentOffset
跟踪滚动视图滚动,因为scrollViewDidScroll在我的应用程序中也会产生一些奇怪的行为。也许你想尝试一下。