3

我试图实现这样一个表格视图来检测滚动量并决定是否显示导航栏。

@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,则预计导航栏会被隐藏。

当我把NSLogforscrollAmount程序运行正确时,它正在隐藏导航。当用户离开顶部或接近顶部并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但效果很好,现在我想知道为什么我的实现失败了。任何想法表示赞赏。

4

1 回答 1

0

代码看起来不错,但如果我是你,我会使用

- (void)scrollViewWillEndDragging:(UIScrollView *)scrollView withVelocity:(CGPoint)velocity targetContentOffset:(inout CGPoint *)targetContentOffset 

跟踪滚动视图的滚动,因为 scrollViewDidScroll 在我的应用程序中也会产生一些奇怪的行为。也许你想试一试。

于 2013-12-14T17:46:13.250 回答