在开发中我们可能会遇到滚动卡片视图的需求,如图
screenshot.png
这个滚动卡片视图中我添加了transform3D旋转缩放
CGFloat isLeft = distance < 0 ? 1:-1;
CGFloat angle = (1- scale) * M_PI_2 * isLeft;
transform3D.m34 = -1 / 500.0;
transform3D = CATransform3DRotate(transform3D, angle, 0, 1, 0);
transform3D = CATransform3DScale(transform3D,scale , scale, 0);
attr.transform3D = transform3D;
滚动效果实现后出现了一个新的问题,就是collectionViewDelegate中
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
该代理方法无法响应执行
解决方案如下:
1.通过scrollView的scrollView.contentSize和scrollView.contentOffset.x来计算当前滚动到第几个item了
2.给collectionView添加手势UITapGestureRecognizer,响应点击方法
贴下代码:
添加手势
UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(didSelectScrollItem)];
[collectionView addGestureRecognizer:tap];
计算滚动到的index
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
CGFloat offsetx = scrollView.contentOffset.x;
CGSize size = scrollView.contentSize;
CGFloat x = size.width;
CGFloat leftW = (kScreen.width - 一个item的宽度)/2;(距离左右两边的宽)
NSInteger num = (offsetx+leftW) / (x/item数量);
if(x == 0){
self.index = 0;
}else{
self.index = num;
}
}
- (void)didSelectScrollItem
{
NSLog(@"%ld",self.index);
}
网友评论