UICollectionView *collectionView = [[UICollectionView alloc]initWithFrame:frame collectionViewLayout:layout];
collectionView.delegate = self;
collectionView.dataSource = self;
[self.view addSubview:collectionView];
UILongPressGestureRecognizer *longPressGesture = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(longPressGesture:)];
longPressGesture.minimumPressDuration = 0.25f;
[collectionView addGestureRecognizer:longPressGesture];
#pragma mark - 开始拖拽
- (void)longPressGesture:(UILongPressGestureRecognizer *)gesture
{
NSIndexPath *selectedIndexPath = [collectionView indexPathForItemAtPoint:[gesture locationInView:collectionView]];
UICollectionViewCell *cell = [collectionView cellForItemAtIndexPath:selectedIndexPath];
switch (gesture.state) {
case UIGestureRecognizerStateBegan:
{
if (selectedIndexPath) {
if (‘你的版本号’ >= 9) {
[collectionView beginInteractiveMovementForItemAtIndexPath:selectedIndexPath];
}
}
break;
}
case UIGestureRecognizerStateChanged:
{
if (!cell || [cell isKindOfClass:[cell class]] ) {
if (‘你的版本号’ >= 9) {
[collectionView endInteractiveMovement];
}
break;
}
@try {
if (‘你的版本号’ >= 9) {
//更新位移
[collectionView updateInteractiveMovementTargetPosition:[gesture locationInView:gesture.view]];
}//如果为空则结束cell位移
} @catch (NSException *exception) {
if (‘你的版本号’ >= 9) {
[collectionView endInteractiveMovement];
}
} @finally {
}
break;
}
case UIGestureRecognizerStateEnded:
{
if (‘你的版本号’ >= 9) {
//结束位移
[collectionView endInteractiveMovement];
}
break;
}
default:
{
if (‘你的版本号’ >= 9) {
[collectionView cancelInteractiveMovement];
}
break;
}
}
}