UIScrollView did Scroll

CodeGeek123 picture CodeGeek123 · Sep 19, 2012 · Viewed 12.1k times · Source

I want to show an image that stays on the page for 5 seconds but appears everytime my scrollview scrolls. So obviously i need to marry animation for the UILabel and some method of UIScrollView. Im not sure which one to use to be honest. Also i have two UIScrollViews on one UIViewController so i dont know what i should set as delegate.

The following is the animation i have at the moment

 [UIView animateWithDuration:0.3 animations:^{  // animate the following:
    pageCountImage.frame = CGRectMake(0, 0, 100, 50); // move to new location
}];

Answer

danh picture danh · Sep 19, 2012

Your view controller can be the delegate of both scroll views. Agree with @Ravi that you can use the delegate param to determine which scroll view is scrolling.

Sounds like you need a few animations packaged to make sense for the UI:

// hide or show the page count image after a given delay, invoke completion when done
- (void)setPageCountImageHidden:(BOOL)hidden delay:(NSTimeInterval)delay completion:(void (^)(BOOL))completion {

    BOOL currentlyHidden = self.pageCountImage.alpha == 0.0;
    if (hidden == currentlyHidden) return;

    [UIView animateWithDuration:0.3 delay:delay options:UIViewAnimationOptionBeginFromCurrentState animations:^{
        self.pageCountImage.alpha = (hidden)? 0.0 : 1.0;
    } completion:completion];
}

// move the page count image to the correct position given a scroll view content offset
- (void)positionPageControlForContentOffset:(CGFloat)xOffset {

    // assume page width is a constant (the width of a page in the scroll view)
    NSInteger page = xOffset / kPAGEWIDTH;

    // assume max page is a constant (the max number of pages in scroll view)
    // scroll positions in the "bounce" will generate page numbers out of bounds, fix that here...
    page = MAX(MIN(page, kMAXPAGE), 0);

    // kPAGE_INDICATOR_WIDTH the distance the page image moves between pages
    // kPAGE_INDICATOR_ORIGIN the page image x position at page zero
    CGFloat xPosition = kPAGE_INDICATOR_ORIGIN + page * kPAGE_INDICATOR_WIDTH;

    // assume y position and size are constants
    CGRect pageIndicatorFrame = CGRectMake(xPosition, kYPOS, kWIDTH, kHEIGHT);

    // finally, do the animation
    [UIView animateWithDuration:0.3 animations:^{
        self.pageCountImage.frame = pageIndicatorFrame;
    }];
}

Then in view did scroll:

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {

    if (scrollView == /* the scroller with the page control */) {

        [self setPageCountImageHidden:NO delay:0.0 completion:^(BOOL finished) {
            [self positionPageControlForContentOffset:scrollView.contentOffset.x];
            [self setPageCountImageHidden:YES delay:5.0 completion:^(BOOL finished){}];
        }];
    }
    // and so on...