Fry
Fry

Reputation: 6275

UIScrollView with fixed contents inside

my question is: In my app I want realize somethings like this using UIScrollView

enter image description here

A UIScrollView whit all his contents inside. But when I reached the top of the screen (or maybe the bottom of the screen) I want to anchor some contents like in the AppStore (iOS 6).

enter image description here

In this case the "Detail", "Review" and "Related" buttons stop scrolling and remains fixed at the top.

Anyone have any idea how to do?

Upvotes: 3

Views: 3877

Answers (2)

rob mayoff
rob mayoff

Reputation: 386018

Give your scroll view a delegate if it doesn't already have one. This would probably be your view controller.

Also give the delegate a reference to the floating view. (In the example, the floating view contains the “Dettagli”, “Recensioni”, and “Correlati” buttons, and the floating view is transparent where the triangular notch is, and the shadow is also part of the floating view.) The floating view must be a subview of the scroll view.

Save the “normal” Y coordinate of the floating view's frame in an instance variable. For example, if the delegate is a view controller, you should probably do it in viewDidLoad:

- (void)viewDidLoad {
    [super viewDidLoad];
    originalFloatingViewY = floatingView.frame.origin.y;
}

In the delegate's scrollViewDidScroll: method, check whether the scroll view has been scrolled below the top of the “normal” position of the floating view. If so, move the floating view to the top edge of the visible area:

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    [self updateFloatingViewFrame];
}

- (void)updateFloatingViewFrame {
    CGPoint contentOffset = scrollView.contentOffset;

    // The floating view should be at its original position or at top of
    // the visible area, whichever is lower.
    CGFloat y = MAX(contentOffset.y, originalFloatingViewY);

    CGRect frame = floatingView.frame;
    if (y != frame.origin.y) {
        frame.origin.y = y;
        floatingView.frame = frame;
    }
}

You could also do it by subclassing UIScrollView and overriding layoutSubviews. Watch the “Advanced ScrollView Techniques” video from WWDC 2011 for more information on this technique.

Upvotes: 8

iDev
iDev

Reputation: 23278

You need to handle this in the UIScrollView's delegate method( scrollViewDidScroll:) for scrolling. When the y of scrollview reaches that particular value you need to disable scrolling in this direction alone. You just need to add an if condition there to check and reset the y point while scrolling. For this you might have to keep this particular portion as a separate scrollview outside the below content and move it along with the below scroll view's upward movement.

Upvotes: 0

Related Questions