如圖,動(dòng)畫不清楚,看效果請(qǐng)移步github
下載
swift版本
OC版本
原理:監(jiān)聽cell的滾動(dòng),對(duì)屏幕區(qū)域內(nèi)可見cell內(nèi)部圖片設(shè)置偏移差
cell設(shè)置
// 宏定義圖片高度
#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;
}
核心方法
在控制器中監(jiān)聽cell滾動(dòng),遍歷屏幕中可見cell,不停的設(shè)置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);
}
}