Graham
Graham

Reputation: 6562

iOS UIView scrolling UI - how to implement?

Forgive me to the obtuse title, as I'm unsure how to describe this question.

Recently many iOS apps utilise a scrolling UI design pattern which helps to maximise screen real-estate, typically hiding the header when the user scrolls downwards.

For example, Instragram's main view has the Instragram header at the top. Scrolling upwards on this view keeps the header fixed at the top, and the view bounces back normally to the top of the content. But scroll down and the header acts as part of the content, making way for an extra 44 points of vertical space.

Its probably that I haven't done much iOS work in a while, but I can't easily figure out how best to impliment this? Apologies for the terrible description.

Upvotes: 0

Views: 1201

Answers (2)

Graham
Graham

Reputation: 6562

I tried ranReloaded's answer above but it seems that calling setFrame: on a UIScrollView stops the view from bouncing when going beyond its bounds.

Instead I set the scroll view to fit inside another UIView called scrollerWrapper. Applying the calculated origin and height to this view gives me effect I'm after plus retains the bounce behaviour.

- (void)scrollViewDidScroll:(UIScrollView*) scrollView
{
    CGPoint offset = scrollView.contentOffset;

    CGRect headerFrame = header.frame;
    CGRect wrapperFrame = scrollerWrapper.frame;

    if(offset.y > 0){
        headerFrame.origin.y = -offset.y;
        wrapperFrame.origin.y = MAX(0, headerFrame.size.height - offset.y);
        }
    else{
        headerFrame.origin.y = 0.0;
        wrapperFrame.origin.y = headerFrame.size.height;
        }
   wrapperFrame.size.height = self.view.frame.size.height - wrapperFrame.origin.y;

    [header setFrame:headerFrame];
    [scrollerWrapper setFrame:wrapperFrame];
}

Upvotes: 1

Nicolas Miari
Nicolas Miari

Reputation: 16246

If the header stays put no matter what, use a separate view on top of the scroll view. If you use UITableView, you can use section headers.

EDIT Use this code:

- (void)scrollViewDidScroll:(UIScrollView*) scrollView
{
    CGPoint offset = scrollView.contentOffset;

    CGRect headerFrame = _headerView.frame;

    if(offset.y > 0){
        headerFrame.origin.y = offset.y;
    }
    else{
        headerFrame.origin.y = 0.0;
    }

    [_headerView setFrame:headerFrame];
}

(Assumes _headerView is your header, sitting on top of the scroll view, not inside it. Also, both scroll view and header begin at the top of their parent view, y==0. Also, your view controller must be set up as delegate of the scroll view)

I just wrote this code from memory; haven't tested it but at most it should only need tweaking.

Upvotes: 1

Related Questions