原文地址:http://blog.csdn.net/u013282507/article/details/54136812
原文講的特別詳細(xì)的畴,在此就是記錄下擎勘,方便查找
要實(shí)現(xiàn)這樣的效果總共分四步:
- 實(shí)現(xiàn)橫向滾動(dòng) (UICollectionView的最基礎(chǔ)實(shí)現(xiàn))
- 縮進(jìn)效果
-(UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout
insetForSectionAtIndex:(NSInteger)section
{
return UIEdgeInsetsMake(0, [self collectionInset], 0, [self collectionInset]);
}
-
居中放大
重寫UICollectionViewFlowLayout方法 -(NSArray<UICollectionViewLayoutAttributes *> *)layoutAttributesForElementsInRect:(CGRect)rect { NSArray *arr = [self getCopyOfAttributes:[super layoutAttributesForElementsInRect:rect]]; //屏幕中線 CGFloat centerX = self.collectionView.contentOffset.x + self.collectionView.bounds.size.width/2.0f; //刷新cell縮放 for (UICollectionViewLayoutAttributes *attributes in arr) { CGFloat distance = fabs(attributes.center.x - centerX); //移動(dòng)的距離和屏幕寬度的的比例 CGFloat apartScale = distance/self.collectionView.bounds.size.width; //把卡片移動(dòng)范圍固定到 -π/4到 +π/4這一個(gè)范圍內(nèi) CGFloat scale = fabs(cos(apartScale * M_PI/4)); //設(shè)置cell的縮放 按照余弦函數(shù)曲線 越居中越趨近于1 attributes.transform = CGAffineTransformMakeScale(1.0, scale); } return arr }
//防止報(bào)錯(cuò) 先復(fù)制attributes
- (NSArray *)getCopyOfAttributes:(NSArray *)attributes
{
NSMutableArray *copyArr = [NSMutableArray new];
for (UICollectionViewLayoutAttributes *attribute in attributes) {
[copyArr addObject:[attribute copy]];
}
return copyArr;
}
//是否需要重新計(jì)算布局
-(BOOL)shouldInvalidateLayoutForBoundsChange:(CGRect)newBounds
{
return true;
} - (NSArray *)getCopyOfAttributes:(NSArray *)attributes
-
自動(dòng)居中
NSInteger _currentIndex; CGFloat _dragStartX; CGFloat _dragEndX;
//手指拖動(dòng)開始
-(void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
_dragStartX = scrollView.contentOffset.x;
}//手指拖動(dòng)停止
-(void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
{
_dragEndX = scrollView.contentOffset.x;
dispatch_async(dispatch_get_main_queue(), ^{
[self fixCellToCenter];
});
}//配置cell居中
-(void)fixCellToCenter
{
//最小滾動(dòng)距離
float dragMiniDistance = self.bounds.size.width/20.0f;
if (_dragStartX - _dragEndX >= dragMiniDistance) {
_currentIndex -= 1;//向右
}else if(_dragEndX - _dragStartX >= dragMiniDistance){
_currentIndex += 1;//向左
}
NSInteger maxIndex = [_collectionView numberOfItemsInSection:0] - 1;
_currentIndex = _currentIndex <= 0 ? 0 : _currentIndex;
_currentIndex = _currentIndex >= maxIndex ? maxIndex : _currentIndex;[_collectionView scrollToItemAtIndexPath:[NSIndexPath indexPathForRow:_currentIndex inSection:0] atScrollPosition:UICollectionViewScrollPositionCenteredHorizontally animated:YES];
}