Wesley
Wesley

Reputation: 2200

Rotate wheel based on scrolling in a UIScrollView

I am trying to make a wheel rotate smoothly based on scrolling of a UIScrollView. I would want it to ease out when it almost stops scrolling the scrollview.

I tried much but failed so far, my current code is this:

#pragma mark - Scrollview delegate

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    CGFloat pageWidth = scrollView.frame.size.width;
    int page = floor((scrollView.contentOffset.x - pageWidth / 2) / pageWidth) + 1;
    NSLog(@"Offset: %@ Page: %i", NSStringFromCGPoint(scrollView.contentOffset), page);

    UIImageView* leftWheelImageView = (UIImageView*)[self.carImageView viewWithTag:10];

    // Calculate speed of scrolling and turn the wheels to it
    CGPoint currentOffset = scrollView.contentOffset;
    NSTimeInterval currentTime = [NSDate timeIntervalSinceReferenceDate];

    if(lastTime - currentTime > 0.1) {
        CGFloat distance = currentOffset.x - lastOffset.x;
        CGFloat scrollSpeedNotAbs = (distance * 10) / 1000; //in pixels per millisecond        
        CGFloat scrollSpeed = fabsf(scrollSpeedNotAbs);

        leftWheelImageView.transform = CGAffineTransformMakeRotation(DEGREES_TO_RADIANS(2*3.14*99));
        NSLog(@"Rotate wheel");
    }

    lastOffset = currentOffset;
    lastTime = currentTime;
}

Could anyone push me in the right direction :-)?

Upvotes: 3

Views: 987

Answers (2)

V-Xtreme
V-Xtreme

Reputation: 7333

Why don't you use the library for doing this ? I have done this using carousel library . Please refer following link https://github.com/nicklockwood/iCarousel this is easy and better to implement.

Upvotes: 2

Dustin
Dustin

Reputation: 6803

You're setting your offset and time incorrectly; as it is, lastOffset and lastTime are being changed to currentOffset and currentTime every time you get the didScroll message. So your if statement will only be triggered if there's more than .1 seconds between each message. Since you said you wanted your scrolling to be smooth, it seems unlikely that this is what you were intending. Maybe move your assignments inside of your if statement? I'll see if I can find another method for you to use.

Upvotes: 3

Related Questions