开发者

Rotate View While Scrolling

Pretty simple Question:

I have a ScrollView and an ImageView. 开发者_StackOverflowFor every pixel scrolled, the ImageView should rotate a certain amount of degrees.

Any ideas how to do this? Thanks in advance


Implement UIScrollViewDelegate and rotate with an affine transform.

#import <QuartzCore/QuartzCore.h>

- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    CGPoint offset = scrollView.contentOffset;
    CGFloat rotateDegrees = offset.y;
    CGFloat rotateRadians = rotateDegrees * (M_PI / 180);
    _myImage.layer.affineTransform = CGAffineTransformMakeRotation(rotateRadians);
}

To reset the rotation, use _myImage.layer.affineTransform = CGAffineTransformIdentity.


Assign a delegate for the scroll view and implement the -scrollViewDidScroll: method. This gets called every time the scroll view moves. In that method, get the contentOffset of the scroll view, and compare it to some saved initial state. That gets you the number of pixels/points scrolled.

Figure out how much you want to rotate the image as a result, and create a rotation transform with CGAffineTransformMakeRotation (docs), and assign it to the image view's transform property.


Vertical scrolling and Swift 5:

func scrollViewDidScroll(_ scrollView: UIScrollView) {
    let topOffset = scrollView.contentOffset.y
    let angle = -topOffset * 2 * CGFloat(Double.pi / 180)
    self.myImageView.transform = CGAffineTransform(rotationAngle: angle)
}

And, yeah, don't forget to do this in viewDidLoad:

self.scrollView.delegate = self
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜