热门标签 | HotTags
当前位置:  开发笔记 > IOS > 正文

iOS开发UICollectionView实现拖拽效果

这篇文章主要为大家详细介绍了iOS开发UICollectionView实现拖拽效果,具有一定的参考价值,感兴趣的小伙伴们可以参考一下

一.介绍

iOS9提供API实现单元格排序功能,使用UICollectionView及其代理方法。iOS9之后有自带方法可以实现该效果,只需添加长按手势,实现手势方法和调用iOS9的API交换数据,iOS9之前需要自己写方法实现这效果,除了要添加长按手势,这里还需要利用截图替换原理,手动计算移动位置来处理视图交换和数据交换。

二.方法和步骤

1.创建工程项目和视图控制器,如下图

2.声明对象和设置代理和数据源代理

@interface ViewController ()
 
@property (nonatomic, strong) NSMutableArray *dataArr;
@property (nonatomic, strong) UICollectionView *collectionView;
/**之前选中cell的NSIndexPath*/
@property (nonatomic, strong) NSIndexPath *oldIndexPath;
/**单元格的截图*/
@property (nonatomic, strong) UIView *snapshotView;
/**之前选中cell的NSIndexPath*/
@property (nonatomic, strong) NSIndexPath *moveIndexPath;
 
@end

3.初始化UICollectionView,并添加长按手势,在viewDidLoad中初始化

CGFloat SCREEN_WIDTH = self.view.frame.size.width;
  UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
  flowLayout.itemSize = CGSizeMake((SCREEN_WIDTH-40.0)/3, (SCREEN_WIDTH-40.0)/3);
  UICollectionView *collectiOnView= [[UICollectionView alloc] initWithFrame:CGRectMake(0, 50.0, SCREEN_WIDTH, (SCREEN_WIDTH-40.0)/3+20.0) collectionViewLayout:flowLayout];
  collectionView.dataSource = self;
  collectionView.delegate = self;
  collectionView.backgroundColor = [UIColor whiteColor];
  [collectionView registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:@"uicollectionviewcell"];
  [self.view addSubview:self.collectiOnView= collectionView];
  
  // 添加长按手势
  UILongPressGestureRecognizer *lOngPress= [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(handlelongGesture:)];
  [collectionView addGestureRecognizer:longPress];

4.实例化数据源,(50个随机颜色,透明度0.8),在viewDidLoad中初始化

self.dataArr = [[NSMutableArray alloc] init];
for (NSInteger index = 0; index <50; index ++) {
    CGFloat hue = (arc4random()%256/256.0); //0.0 到 1.0
    CGFloat saturation = (arc4random()%128/256.0)+0.5; //0.5 到 1.0
    CGFloat brightness = (arc4random()%128/256.0)+0.5; //0.5 到 1.0
    UIColor *color = [UIColor colorWithHue:hue saturation:saturation brightness:brightness alpha:0.5];
    [self.dataArr addObject:color];
  }

5.实现UICollectionView的UICollectionViewDataSource的两个必须实现的方法

#pragma mark - UICollectionViewDataSource
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
  return self.dataArr.count;
}
 
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
  UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"uicollectionviewcell" forIndexPath:indexPath];
  cell.backgroundColor = self.dataArr[indexPath.row];
  return cell;
}

6.重点来了,实现长按手势方法

#pragma mark - 长按手势
- (void)handlelongGesture:(UILongPressGestureRecognizer *)longPress
{
  if ([[[UIDevice currentDevice] systemVersion] floatValue] <9.0) {
    [self action:longPress];
  } else {
    [self iOS9_Action:longPress];
  }
}

7.iOS9之后的实现

#pragma mark - iOS9 之后的方法
- (BOOL)collectionView:(UICollectionView *)collectionView canMoveItemAtIndexPath:(NSIndexPath *)indexPath
{
  // 返回YES允许row移动
  return YES;
}
 
- (void)collectionView:(UICollectionView *)collectionView moveItemAtIndexPath:(NSIndexPath *)sourceIndexPath toIndexPath:(NSIndexPath *)destinationIndexPath
{
  //取出移动row数据
  id color = self.dataArr[sourceIndexPath.row];
  //从数据源中移除该数据
  [self.dataArr removeObject:color];
  //将数据插入到数据源中的目标位置
  [self.dataArr insertObject:color atIndex:destinationIndexPath.row];
}
 
- (void)iOS9_Action:(UILongPressGestureRecognizer *)longPress
{
  switch (longPress.state) {
    case UIGestureRecognizerStateBegan:
    { //手势开始
      //判断手势落点位置是否在row上
      NSIndexPath *indexPath = [self.collectionView indexPathForItemAtPoint:[longPress locationInView:self.collectionView]];
      if (indexPath == nil) {
        break;
      }
      UICollectionViewCell *cell = [self.collectionView cellForItemAtIndexPath:indexPath];
      [self.view bringSubviewToFront:cell];
      //iOS9方法 移动cell
      [self.collectionView beginInteractiveMovementForItemAtIndexPath:indexPath];
    }
      break;
    case UIGestureRecognizerStateChanged:
    { // 手势改变
      // iOS9方法 移动过程中随时更新cell位置
      [self.collectionView updateInteractiveMovementTargetPosition:[longPress locationInView:self.collectionView]];
    }
      break;
    case UIGestureRecognizerStateEnded:
    { // 手势结束
      // iOS9方法 移动结束后关闭cell移动
      [self.collectionView endInteractiveMovement];
    }
      break;
    default: //手势其他状态
      [self.collectionView cancelInteractiveMovement];
      break;
  }
}

8.iOS9之前的实现

#pragma mark - iOS9 之前的方法
- (void)action:(UILongPressGestureRecognizer *)longPress
{
  switch (longPress.state) {
    case UIGestureRecognizerStateBegan:
    { // 手势开始
      //判断手势落点位置是否在row上
      NSIndexPath *indexPath = [self.collectionView indexPathForItemAtPoint:[longPress locationInView:self.collectionView]];
      self.oldIndexPath = indexPath;
      if (indexPath == nil) {
        break;
      }
      UICollectionViewCell *cell = [self.collectionView cellForItemAtIndexPath:indexPath];
      // 使用系统的截图功能,得到cell的截图视图
      UIView *snapshotView = [cell snapshotViewAfterScreenUpdates:NO];
      snapshotView.frame = cell.frame;
      [self.view addSubview:self.snapshotView = snapshotView];
      // 截图后隐藏当前cell
      cell.hidden = YES;
      
      CGPoint currentPoint = [longPress locationInView:self.collectionView];
      [UIView animateWithDuration:0.25 animations:^{
        snapshotView.transform = CGAffineTransformMakeScale(1.05, 1.05);
        snapshotView.center = currentPoint;
      }];
    }
      break;
    case UIGestureRecognizerStateChanged:
    { // 手势改变
      //当前手指位置 截图视图位置随着手指移动而移动
      CGPoint currentPoint = [longPress locationInView:self.collectionView];
      self.snapshotView.center = currentPoint;
      // 计算截图视图和哪个可见cell相交
      for (UICollectionViewCell *cell in self.collectionView.visibleCells) {
        // 当前隐藏的cell就不需要交换了,直接continue
        if ([self.collectionView indexPathForCell:cell] == self.oldIndexPath) {
          continue;
        }
        // 计算中心距
        CGFloat space = sqrtf(pow(self.snapshotView.center.x - cell.center.x, 2) + powf(self.snapshotView.center.y - cell.center.y, 2));
        // 如果相交一半就移动
        if (space <= self.snapshotView.bounds.size.width / 2) {
          self.moveIndexPath = [self.collectionView indexPathForCell:cell];
          //移动 会调用willMoveToIndexPath方法更新数据源
          [self.collectionView moveItemAtIndexPath:self.oldIndexPath toIndexPath:self.moveIndexPath];
          //设置移动后的起始indexPath
          self.oldIndexPath = self.moveIndexPath;
          break;
        }
      }
    }
      break;
    default:
    { // 手势结束和其他状态
      UICollectionViewCell *cell = [self.collectionView cellForItemAtIndexPath:self.oldIndexPath];
      // 结束动画过程中停止交互,防止出问题
      self.collectionView.userInteractiOnEnabled= NO;
      // 给截图视图一个动画移动到隐藏cell的新位置
      [UIView animateWithDuration:0.25 animations:^{
        self.snapshotView.center = cell.center;
        self.snapshotView.transform = CGAffineTransformMakeScale(1.0, 1.0);
      } completion:^(BOOL finished) {
        // 移除截图视图,显示隐藏的cell并开始交互
        [self.snapshotView removeFromSuperview];
        cell.hidden = NO;
        self.collectionView.userInteractiOnEnabled= YES;
      }];
    }
      break;
  }
}

三.iOS9之后添加的API如下

// Support for reordering
- (BOOL)beginInteractiveMovementForItemAtIndexPath:(NSIndexPath *)indexPath NS_AVAILABLE_IOS(9_0); // returns NO if reordering was prevented from beginning - otherwise YES
- (void)updateInteractiveMovementTargetPosition:(CGPoint)targetPosition NS_AVAILABLE_IOS(9_0);
- (void)endInteractiveMovement NS_AVAILABLE_IOS(9_0);
- (void)cancelInteractiveMovement NS_AVAILABLE_IOS(9_0);


以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。


推荐阅读
  • 本文介绍了如何找到并终止在8080端口上运行的进程的方法,通过使用终端命令lsof -i :8080可以获取在该端口上运行的所有进程的输出,并使用kill命令终止指定进程的运行。 ... [详细]
  • 本文讨论了如何优化解决hdu 1003 java题目的动态规划方法,通过分析加法规则和最大和的性质,提出了一种优化的思路。具体方法是,当从1加到n为负时,即sum(1,n)sum(n,s),可以继续加法计算。同时,还考虑了两种特殊情况:都是负数的情况和有0的情况。最后,通过使用Scanner类来获取输入数据。 ... [详细]
  • Android Studio Bumblebee | 2021.1.1(大黄蜂版本使用介绍)
    本文介绍了Android Studio Bumblebee | 2021.1.1(大黄蜂版本)的使用方法和相关知识,包括Gradle的介绍、设备管理器的配置、无线调试、新版本问题等内容。同时还提供了更新版本的下载地址和启动页面截图。 ... [详细]
  • 本文介绍了一种划分和计数油田地块的方法。根据给定的条件,通过遍历和DFS算法,将符合条件的地块标记为不符合条件的地块,并进行计数。同时,还介绍了如何判断点是否在给定范围内的方法。 ... [详细]
  • 本文讲述了作者通过点火测试男友的性格和承受能力,以考验婚姻问题。作者故意不安慰男友并再次点火,观察他的反应。这个行为是善意的玩人,旨在了解男友的性格和避免婚姻问题。 ... [详细]
  • 安卓select模态框样式改变_微软Office风格的多端(Web、安卓、iOS)组件库——Fabric UI...
    介绍FabricUI是微软开源的一套Office风格的多端组件库,共有三套针对性的组件,分别适用于web、android以及iOS,Fab ... [详细]
  • 本文介绍了多因子选股模型在实际中的构建步骤,包括风险源分析、因子筛选和体系构建,并进行了模拟实证回测。在风险源分析中,从宏观、行业、公司和特殊因素四个角度分析了影响资产价格的因素。具体包括宏观经济运行和宏经济政策对证券市场的影响,以及行业类型、行业生命周期和行业政策对股票价格的影响。 ... [详细]
  • 宁德时代与第四范式达成合作,将利用第四范式的AI技术,打造规模化的人工智能平台,并将AI技术融入电池生产线。通过全流程AI技术和低门槛的AI生产工具,宁德时代实现了对生产线数据的实时分析与决策。第四范式是一家人工智能技术与服务提供商,其先知平台降低了AI在各行业内的应用门槛。宁德时代是国内具备国际竞争力的动力电池制造商之一,专注于新能源汽车动力电池系统、储能系统的研发、生产和销售。 ... [详细]
  • 本文介绍了P1651题目的描述和要求,以及计算能搭建的塔的最大高度的方法。通过动态规划和状压技术,将问题转化为求解差值的问题,并定义了相应的状态。最终得出了计算最大高度的解法。 ... [详细]
  • 1,关于死锁的理解死锁,我们可以简单的理解为是两个线程同时使用同一资源,两个线程又得不到相应的资源而造成永无相互等待的情况。 2,模拟死锁背景介绍:我们创建一个朋友 ... [详细]
  • 解决Cydia数据库错误:could not open file /var/lib/dpkg/status 的方法
    本文介绍了解决iOS系统中Cydia数据库错误的方法。通过使用苹果电脑上的Impactor工具和NewTerm软件,以及ifunbox工具和终端命令,可以解决该问题。具体步骤包括下载所需工具、连接手机到电脑、安装NewTerm、下载ifunbox并注册Dropbox账号、下载并解压lib.zip文件、将lib文件夹拖入Books文件夹中,并将lib文件夹拷贝到/var/目录下。以上方法适用于已经越狱且出现Cydia数据库错误的iPhone手机。 ... [详细]
  • 本文介绍了解决二叉树层序创建问题的方法。通过使用队列结构体和二叉树结构体,实现了入队和出队操作,并提供了判断队列是否为空的函数。详细介绍了解决该问题的步骤和流程。 ... [详细]
  • 本文讨论了使用HTML5+JS开发App所需的框架和工具推荐,希望能提供真实案例作为参考。重点考虑框架和工具的文档齐全性以及是否支持二维码扫描、摇一摇等功能。同时提到了H5+框架的适用性。 ... [详细]
  • 本文介绍了一个程序,可以输出1000内能被3整除且个位数为6的所有整数。程序使用了循环和条件判断语句来筛选符合条件的整数,并将其输出。 ... [详细]
  • 《数据结构》学习笔记3——串匹配算法性能评估
    本文主要讨论串匹配算法的性能评估,包括模式匹配、字符种类数量、算法复杂度等内容。通过借助C++中的头文件和库,可以实现对串的匹配操作。其中蛮力算法的复杂度为O(m*n),通过随机取出长度为m的子串作为模式P,在文本T中进行匹配,统计平均复杂度。对于成功和失败的匹配分别进行测试,分析其平均复杂度。详情请参考相关学习资源。 ... [详细]
author-avatar
化工12卓越团支部CUP
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有