我有这段代码:
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
UINavigationBar *navbar =self.navigationController.navigationBar;
UIView *tableView = self.view;
CGRect navBarFrame = self.navigationController.navigationBar.frame;
CGRect tableFrame = self.view.frame;
//changing the origin.y based on the current scroll view.
//Adding +20 for the Status Bar since the offset is tied into that.
navBarFrame.origin.y = MIN(0, MAX(-44, (scrollView.contentOffset.y * -1))) +20 ;
tableFrame.origin.y = navBarFrame.origin.y + navBarFrame.size.height;
navbar.frame = navBarFrame;
tableView.frame = tableFrame;
}
这会产生隐藏导航栏所需的效果,但只有滚动到滚动视图的顶部(y offset = 0)才会重新显示导航。如何在每次向上滚动时重新显示导航栏的行为?
答案 0 :(得分:2)
我已经取消了手动框架代码,以获得更直观的代码:
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
if (lastContentOffset > scrollView.contentOffset.y) {
if (downwards) {
downwards = NO;
scrollDistance = 0;
} else {
scrollDistance++;
}
}
else if (lastContentOffset < scrollView.contentOffset.y) {
if (!downwards) {
downwards = YES;
scrollDistance = 0;
} else {
scrollDistance++;
}
}
lastContentOffset = scrollView.contentOffset.y;
CGFloat threshold = 10;
if (downwards && !self.navigationController.navigationBarHidden && scrollDistance > threshold) {
[self.navigationController setNavigationBarHidden:YES animated:YES];
} else if (!downwards && self.navigationController.navigationBarHidden && scrollDistance > threshold) {
[self.navigationController setNavigationBarHidden:NO animated:YES];
}
}
这也会增加一个10px的阈值,这样它只会对有意义的向上或向下滚动做出反应
答案 1 :(得分:1)
使用此链接检测滚动方向:Detect Scroll Direction
我真的不明白你对你发布的代码做了什么。您是每次都创建一个新的导航栏还是隐藏并显示相同的导航栏?
无论如何,一旦检测到滚动方向,只需在ScrollDirection = ScrollDirectionUp
时显示导航栏。
类似的东西:
if (ScrollDirection == ScrollDirectionUp) {
self.navigationController.navigationBar.hidden = NO;
}