ios UICollectionView滑动时操作

时间:2023-03-08 22:48:17
ios UICollectionView滑动时操作

点开UICollectionViewDelegate,发现有@protocol UICollectionViewDelegate <UIScrollViewDelegate>。

所以只要实现UIScrollViewDelegate的

- (void)scrollViewDidScroll:(UIScrollView *)scrollView; 方法,就可以重写UICollectionView滑动操作

例如,在UICollection上方有一个名为testImg的ImageView,要跟着UICollection的滑动一起动,那么可以使用下面方法

 - (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
CGPoint point=scrollView.contentOffset;
NSLog(@"%f,%f",point.x,point.y); CGRect frame = [_testImg frame];
frame.origin.y = -point.y;
_testImg.frame = frame; frame = [scrollView frame];
frame.origin.y = -point.y;
scrollView.frame = frame;
}

需要注意的是,第7行的43和第11行的179分别为testImg和UICollectionView初始的y轴值,不是滑动之前的值。如果使用

控件.origin.y -= point.y;

y值就会快速变小,控件瞬间飞出屏幕

上述代码中,point是滑动之后的偏移量,手指上滑,偏移y为正