推拉.gif
之前在某款A(yù)PP中看到了這種照片瀏覽效果,驚艷之余也用心思考并實(shí)現(xiàn)了出來贝搁,現(xiàn)在特地拿出來分享給大家郑气。
1.思路
看到這種效果的時(shí)候,首先?猜測是用UICollectionView實(shí)現(xiàn)的乌昔,但是正常的UICollectionView的每個(gè)Cell都是首尾相連的隙疚,現(xiàn)在卻是每個(gè)Cell都在上一個(gè)Cell的正下方,因此我猜測是在滑動的時(shí)候?qū)⑾乱粋€(gè)Cell插入到正在滑動的Cell的下方并隨著Y軸方向的偏移量而移動磕道。
2.實(shí)現(xiàn)
核心代碼:
- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
if (scrollView.contentOffset.y < 0) {//頂部第一個(gè)cell下拉不產(chǎn)生效果
return;
}
//獲取到當(dāng)前cell
int offset = scrollView.contentOffset.y / [UIScreen mainScreen].bounds.size.height ;
NSIndexPath *index = [NSIndexPath indexPathForItem:offset inSection:0];
UICollectionViewCell *cell = [self.collectionView cellForItemAtIndexPath:index];
//獲取到下一個(gè)cell
NSIndexPath *nextIndex = [NSIndexPath indexPathForItem:offset + 1 inSection:0];
UICollectionViewCell *nextCell = [self.collectionView cellForItemAtIndexPath:nextIndex];
//將下一個(gè)cell插入到當(dāng)前cell的下方并隨著Y軸方向的偏移量而移動
CGRect rect = nextCell.frame;
rect.origin.y = scrollView.contentOffset.y;
nextCell.frame = rect;
[self.collectionView insertSubview:nextCell belowSubview:cell];
//下拉設(shè)置透明度
if (scrollView.contentOffset.y < self.offsetY) {
CGFloat progress = (self.offsetY - scrollView.contentOffset.y) / [UIScreen mainScreen].bounds.size.height;
cell.alpha = progress;
self.currentCell = nil;
self.currentCell = cell;
}
}
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
[self adjustCurrentCell:scrollView];//暫時(shí)修復(fù)底部間隙BUG供屉,待修改,還望大家指導(dǎo)
self.offsetY = scrollView.contentOffset.y;
self.currentCell.alpha = 1.0;
}
- (void)adjustCurrentCell:(UIScrollView *)scrollView {
//獲取到當(dāng)前cell
NSInteger offset = scrollView.contentOffset.y / [UIScreen mainScreen].bounds.size.height ;
NSIndexPath *index = [NSIndexPath indexPathForItem:offset inSection:0];
UICollectionViewCell *cell = [self.collectionView cellForItemAtIndexPath:index];
CGRect rect = cell.frame;
rect.origin.y = self.collectionView.contentOffset.y;
cell.frame = rect;
}
3.源碼
初步效果就這樣了溺蕉,具體使用就仁者見仁伶丐、智者見智了。源碼放在gitHub上疯特,歡迎大家指正哗魂,記得?star哦!