iOS开发

UICollectionView可拖动,并且某个cell不能动

2022-03-14  本文已影响0人  滴滴滴开门

第一步给cell添加长按方法

    UILongPressGestureRecognizer *lgest = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(longclick:)];
    if (self.isedit) {
        if ([model.isDefault isEqualToString:@"1"]) {//不能移动的
            cell.Image_Icon.hidden =YES;
            [cell removeGestureRecognizer:lgest];
        }else
        {
            [cell addGestureRecognizer:lgest];
        }
        
    }else
    {
        [cell removeGestureRecognizer:lgest];
    }

第二步触发的方法

-(void)longclick:(UIGestureRecognizer *)gar{

switch (gar.state) {

  case UIGestureRecognizerStateBegan:

      if([self.collectionView indexPathForItemAtPoint:[gar locationInView:self.collectionView]] == nil){

         break;

      }

      [self.collectionView beginInteractiveMovementForItemAtIndexPath:[self.collectionView indexPathForItemAtPoint:[gar locationInView:self.collectionView]]];

      

      break;

  case UIGestureRecognizerStateChanged:
   {
       //固定某个Cell不能移动
       NSIndexPath *indexPath = [self.collectionView indexPathForItemAtPoint:[gar locationInView:self.collectionView]];
       
       MenuInfoModel *model =self.dataSource[indexPath.row];
       if ([model.isDefault isEqualToString:@"1"]) {
           return;
       }
       
       [self.collectionView updateInteractiveMovementTargetPosition:[gar locationInView:self.collectionView]];
   }
         
    
      break;

  case UIGestureRecognizerStateEnded:

      [self.collectionView endInteractiveMovement];

      

      break;

  default:

      [self.collectionView cancelInteractiveMovement];

      break;

}

}

//第三步:设定单位格可移动

-(BOOL)collectionView:(UICollectionView *)collectionView canMoveItemAtIndexPath:(NSIndexPath *)indexPath{

return YES;

}

//第四步:改变数据源顺序

-(void)collectionView:(UICollectionView *)collectionView moveItemAtIndexPath:(NSIndexPath *)sourceIndexPath toIndexPath:(NSIndexPath *)destinationIndexPath{

// FLmodel *model = [_dataSource objectAtIndex:sourceIndexPath.item];
MenuInfoModel *model =[self.dataSource objectAtIndex:sourceIndexPath.item];

[_dataSource removeObject:model];

[_dataSource insertObject:model atIndex:destinationIndexPath.item];

}

上一篇下一篇

猜你喜欢

热点阅读