如图,动画不清楚,看效果请移步github
下载
swift版本
OC版本
原理:监听cell的滚动,对屏幕区域内可见cell内部图片设置偏移差
cell设置
// 宏定义图片高度
#define IMAGE_HEIGHT 200
// 宏定义图片偏移速度
#define IMAGE_OFFSET_SPEED 25
/*
image used in the cell which will be having the parallax effect
*/
@property (nonatomic, strong, readwrite) UIImage *image;
/*
Image will always animate according to the imageOffset provided. Higher the value means higher offset for the image
*/
@property (nonatomic, assign, readwrite) CGPoint imageOffset;
# pragma mark - Setters
- (void)setImage:(UIImage *)image
{
// Store image
self.MJImageView.image = image;
// Update padding
[self setImageOffset:self.imageOffset];
}
- (void)setImageOffset:(CGPoint)imageOffset
{
// Store padding value
_imageOffset = imageOffset;
// Grow image view
CGRect frame = self.MJImageView.bounds;
CGRect offsetFrame = CGRectOffset(frame, _imageOffset.x, _imageOffset.y);
self.MJImageView.frame = offsetFrame;
}
核心方法
在控制器中监听cell滚动,遍历屏幕中可见cell,不停的设置cell中图片的offset
#pragma mark - UIScrollViewdelegate methods
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
for(MJCollectionViewCell *view in self.parallaxCollectionView.visibleCells) {
CGFloat yOffset = ((self.parallaxCollectionView.contentOffset.y - view.frame.origin.y) / IMAGE_HEIGHT) * IMAGE_OFFSET_SPEED;
view.imageOffset = CGPointMake(0.0f, yOffset);
}
}
网友评论