Reputation: 3134
I have this snippet of code:
- (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;
}
this gives the desired effect of hiding my navigation bar, but the navigation will only re-appear if you scroll to the top of the scrollview (y offset = 0). how can I recreate Instagram's behaviour where the navbar reappears whenever you scroll up?
Upvotes: 0
Views: 586
Reputation: 3134
I've scrapped the manual frame code for this more intuitive code:
- (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];
}
}
This also adds a 10px threshold so that it only reacts to a meaningful scroll up or down
Upvotes: 2
Reputation: 3519
Use this link to detect scroll direction: Detect Scroll Direction
I don't really understand what you are doing with your code that you posted. Are you creating a new navigation bar each time or hiding and showing the same one?
Anyways, once you detect scroll direction, just show the navigation bar when ScrollDirection = ScrollDirectionUp
.
Something like:
if (ScrollDirection == ScrollDirectionUp) {
self.navigationController.navigationBar.hidden = NO;
}
Upvotes: 1