0

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?

Halpo
  • 2,555
  • 2
  • 20
  • 48

2 Answers2

2

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

Halpo
  • 2,555
  • 2
  • 20
  • 48
1

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;
}
Community
  • 1
  • 1
MSU_Bulldog
  • 3,465
  • 5
  • 34
  • 73
  • you were right, I ended up messing up my views (I'm using autolayout so the manual frame code didn't work well) - I've added my solution – Halpo Jan 06 '16 at 15:44