我试图实现这样一个表格视图来检测滚动量并决定是否显示导航栏。
@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
forscrollAmount
程序运行正确时,它正在隐藏导航。当用户离开顶部或接近顶部并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
但效果很好,现在我想知道为什么我的实现失败了。任何想法表示赞赏。