长按即可移动Cell的CollectionViewFlowLayout

在很多新闻客户端中都有一个可以排序新闻类别的功能。也用不少通过重写UIScrollView来实现的。这里主要说下通过UICollectionView怎么实现,准确的说是通过CollectionViewFlowLayout来实现。

  • 什么是UICollectionView

UICollectionView是一种新的数据展示方式,简单来说可以把他理解成多列的UITableView(请一定注意这是UICollectionView的最最简单的形式)。如果你用过iBooks的话,可能你还对书架布局有一定印象:一个虚拟书架上放着你下载和购买的各类图书,整齐排列

  • UICollectionView结构

    • Cells 用于展示内容的主体,对于不同的cell可以指定不同尺寸和不同的内容
    • Supplementary Views 追加视图 如果你对UITableView比较熟悉的话,可以理解为每个Section的Header或者Footer,用来标记每个section的view
    • Decoration Views 装饰视图,这是每个section的背景
  • UICollectionViewLayout

UICollectionViewLayout是造就UICollectionView和UITableView最大不同的地方。UICollectionViewLayout可以说是UICollectionView的大脑和中枢,它负责了将各个cell、Supplementary View和Decoration Views进行组织,为它们设定各自的属性,包括但不限于:

  • 位置
  • 尺寸
  • 透明度
  • 层级关系
  • 形状
  • 等等等等…
  • Layout决定了UICollectionView是如何显示在界面上的。在展示之前,一般需要生成合适的UICollectionViewLayout子类对象,并将其赋予CollectionView的collectionViewLayout属性。

长按可移动Cell的UICollectionViewLayout

1、通过UICollectionViewLayout给UICollectionView添加长按事件:主要通过监听layout是否被添加到collectionView中。

-(void)addCollectionCreatedObserver{
  [self addObserver:self forKeyPath:@"collectionView" options:NSKeyValueObservingOptionNew context:nil];
}

2、添加长按手势

-(void)setupCollectionView{
  self.longGestureRecognizer = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(handlerLongPressGesture:)];
  self.longGestureRecognizer.delegate = self;
  [self.collectionView addGestureRecognizer:self.longGestureRecognizer];
}

3、处理手势

-(void)handlerLongPressGesture:(UILongPressGestureRecognizer *)gestureRecognizer{
  switch (gestureRecognizer.state) {
      case UIGestureRecognizerStateBegan:
          [self startLongPressGesture:gestureRecognizer];
          break;
      case UIGestureRecognizerStateChanged:
          [self moveLongPressGesture:gestureRecognizer];
          break;
      case UIGestureRecognizerStateCancelled:
      case UIGestureRecognizerStateEnded:
          [self endLongPressGesture:gestureRecognizer];
          break;
      default:
          break;
  }
}

4、处理手势开始移动操作,主要记录移动的起点,对应的Cell,并对当前Cell做快照,以便移动

  self.startPoint = [gestureRecognizer locationInView:self.collectionView];
  self.selectedMoveIndexPath = currentIndexPath;
  UICollectionViewCell *collectionViewCell = [self.collectionView cellForItemAtIndexPath:self.selectedMoveIndexPath];
  self.currentMoveView = [[UIView alloc] initWithFrame:collectionViewCell.frame];
  collectionViewCell.highlighted = YES;
  
  UIView *highlightedISnapshotView = [collectionViewCell MT_snapshotView];
  highlightedISnapshotView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
  highlightedISnapshotView.alpha = 1.0;
  
  collectionViewCell.highlighted = NO;
  UIView *snapshotView = [collectionViewCell MT_snapshotView];
  snapshotView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
  snapshotView.alpha = 0.0;
  
  [self.currentMoveView addSubview:snapshotView];
  [self.currentMoveView addSubview:highlightedISnapshotView];
  [self.collectionView addSubview:self.currentMoveView];
  self.currentViewCenter = self.currentMoveView.center;

5、处理手势正在移动操作,主要记录坐标变动,并移动快照视图位置:

  CGPoint currentPoint = [gestureRecognizer locationInView:self.collectionView];
  self.currentPoint = CGPointMake(currentPoint.x - self.startPoint.x, currentPoint.y - self.startPoint.y);
  CGPoint viewCenter = self.currentMoveView.center = MT_CGPointAdd(self.currentViewCenter, self.currentPoint);

刷新CollectionView

  NSIndexPath *newIndexPath = [self.collectionView indexPathForItemAtPoint:self.currentMoveView.center];
  NSIndexPath *preIndexPath = self.selectedMoveIndexPath;
  if(newIndexPath == nil || [newIndexPath isEqual:preIndexPath]){
      return;
  }
  self.selectedMoveIndexPath = newIndexPath;
  
  if ([self.collectionView.dataSource respondsToSelector:@selector(collectionView:moveItemAtIndexPath:toIndexPath:)]) {
      [self.collectionView.dataSource collectionView:self.collectionView moveItemAtIndexPath:preIndexPath toIndexPath:newIndexPath];
  }
  __weak typeof(self) weakSelf = self;
  [self.collectionView performBatchUpdates:^{
      [weakSelf.collectionView deleteItemsAtIndexPaths:@[preIndexPath]];
      [weakSelf.collectionView insertItemsAtIndexPaths:@[newIndexPath]];
  } completion:^(BOOL finished) {
      
  }];

6、处理手势结束移动。重置记录:

NSIndexPath *currentIndexPath = self.selectedMoveIndexPath;
self.selectedMoveIndexPath = nil;
self.currentViewCenter = CGPointZero;
[self.currentMoveView removeFromSuperview];
self.currentMoveView = nil;
[self invalidateLayout];
      

7、重载layoutAttributesForElementsInRect:

  -(NSArray *)layoutAttributesForElementsInRect:(CGRect)rect{
    NSArray *layoutAttributesForElementsInRect = [super layoutAttributesForElementsInRect:rect];
    for (UICollectionViewLayoutAttributes *layoutAttributes in layoutAttributesForElementsInRect) {
        if(layoutAttributes.representedElementCategory == UICollectionElementCategoryCell){
            [self applyLayoutAttributes:layoutAttributes];
        }
    }
    return layoutAttributesForElementsInRect;
}

8、重载layoutAttributesForItemAtIndexPath:

-(UICollectionViewLayoutAttributes *)layoutAttributesForItemAtIndexPath:(NSIndexPath *)indexPath{
    UICollectionViewLayoutAttributes *layoutAttributes = [super layoutAttributesForItemAtIndexPath:indexPath];
    if(layoutAttributes.representedElementCategory == UICollectionElementCategoryCell){
        [self applyLayoutAttributes:layoutAttributes];
    }
    return layoutAttributes;
}

9、隐藏当前选择的Cell

-(void)applyLayoutAttributes:(UICollectionViewLayoutAttributes *)layoutAttributes {
  if([layoutAttributes.indexPath isEqual:self.selectedMoveIndexPath]){
      layoutAttributes.hidden = YES;
  }
}

移动Cell时可通知滚动UICollectionView

添加CADisplayLink,来主动触发UICollectionView滚动。

1、创建CADisplayLink

    self.displayLink = [CADisplayLink displayLinkWithTarget:self selector:@selector(handleScroll:)];
    
    [self.displayLink addToRunLoop:[NSRunLoop mainRunLoop] forMode:NSRunLoopCommonModes];

2、处理屏幕刷新事件:

    CGSize frameSize = self.collectionView.bounds.size;
    CGSize contentSize = self.collectionView.contentSize;
    CGPoint contentOffset = self.collectionView.contentOffset;
    UIEdgeInsets contentInset = self.collectionView.contentInset;
    // Important to have an integer `distance` as the `contentOffset` property automatically gets rounded
    // and it would diverge from the view's center resulting in a "cell is slipping away under finger"-bug.
    CGFloat distance = rint(self.scrollingSpeed * displayLink.duration);
    CGPoint translation = CGPointZero;
    ...
    self.collectionView.contentOffset = MT_CGPointAdd(contentOffset, translation);

效果图:

Untitled.gif

完整源码--》Github

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 160,165评论 4 364
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,720评论 1 298
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 109,849评论 0 244
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 44,245评论 0 213
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,596评论 3 288
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,747评论 1 222
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,977评论 2 315
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,708评论 0 204
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,448评论 1 246
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,657评论 2 249
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,141评论 1 261
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,493评论 3 258
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,153评论 3 238
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,108评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,890评论 0 198
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,799评论 2 277
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,685评论 2 272

推荐阅读更多精彩内容

  • 发现 关注 消息 iOS 第三方库、插件、知名博客总结 作者大灰狼的小绵羊哥哥关注 2017.06.26 09:4...
    肇东周阅读 11,623评论 4 59
  • 什么是UICollectionView? UICollectionView是一种新的数据展示方式,简单来说可以把他...
    凌峰Mical阅读 42,190评论 11 201
  • 最近将 UICollectionView 进行了一个全面的学习及总结,参考了网上大量的文章,把官方文档进行了大概翻...
    varlarzh阅读 20,481评论 3 94
  • 地上的剑还在铮鸣, 残阳如血,红了双眼, 听山风四荡,散了这一世英明。 从来无休离愁恨爱, 焚心流泪,终究无奈, ...
    小王爷小王爷阅读 231评论 0 1
  • 1.过滤器创建 了解过滤器常见配置含义 filter-mapping标签里面还有许多参数,可以参考学习博客特别注意...
    丁白一阅读 232评论 0 0