UICollectionView实现放大缩小效果
原文地址:http://blog.csdn.net/u013282507/article/details/54136812
原文讲的特别详细,在此就是记录下,方便查找
20170106123134176.gif 要实现这样的效果总共分四步:
- 实现横向滚动 (UICollectionView的最基础实现)
- 缩进效果
-(UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout
insetForSectionAtIndex:(NSInteger)section
{
return UIEdgeInsetsMake(0, [self collectionInset], 0, [self collectionInset]);
}
- 居中放大
重写UICollectionViewFlowLayout方法-(NSArray
*)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); //移动的距离和屏幕宽度的的比例 CGFloat apartScale = distance/self.collectionView.bounds.size.width; //把卡片移动范围固定到 -π/4到 +π/4这一个范围内 CGFloat scale = fabs(cos(apartScale * M_PI/4)); //设置cell的缩放 按照余弦函数曲线 越居中越趋近于1 attributes.transform = CGAffineTransformMakeScale(1.0, scale); } return arr }
//防止报错 先复制attributes
- (NSArray *)getCopyOfAttributes:(NSArray *)attributes
{
NSMutableArray *copyArr = [NSMutableArray new];
for (UICollectionViewLayoutAttributes *attribute in attributes) {
[copyArr addObject:[attribute copy]];
}
return copyArr;
}
-(BOOL)shouldInvalidateLayoutForBoundsChange:(CGRect)newBounds
{
return true;
}
- (NSArray *)getCopyOfAttributes:(NSArray *)attributes
- 自动居中
NSInteger _currentIndex; CGFloat _dragStartX; CGFloat _dragEndX;
//手指拖动开始
-(void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
_dragStartX = scrollView.contentOffset.x;
}
//手指拖动停止
-(void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
{
_dragEndX = scrollView.contentOffset.x;
dispatch_async(dispatch_get_main_queue(), ^{
[self fixCellToCenter];
});
}
//配置cell居中
-(void)fixCellToCenter
{
//最小滚动距离
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;
【UICollectionView实现放大缩小效果】[_collectionView scrollToItemAtIndexPath:[NSIndexPath indexPathForRow:_currentIndex inSection:0] atScrollPosition:UICollectionViewScrollPositionCenteredHorizontally animated:YES];
}
推荐阅读
- 面向对象——实现类的基本操作
- JavaScript高级语法|ES6——class类实现继承
- 分布式二级缓存组件实战(Redis+Caffeine实现)
- zabbix|Zabbix监控客户端及实现邮件、微信报警
- 五大理由告诉你为什么开发人员选择代码质量静态分析工具Klocwork来实现软件安全
- C++实现双目立体匹配Census算法的示例代码
- Monaco|Monaco Editor实现sql和java代码提示实现示例
- uniapp中用canvas实现小球碰撞的小动画
- UICollectionView的使用
- dgiot-dtu实现PLC数据采集上云实时查看