Swift下使用UICollectionView 实现长按拖拽功能

2020-01-08 23:24:23于丽

导读

简单用Swift写了一个collectionview的拖拽点击排序效果;

拖拽排序是新闻类的App可以说是必有的交互设计,如今日头条,网易新闻等。

GitHub地址:https://www.easck.com/p>

效果

swift,uicollectionview,拖拽

主要代码

手势长按移动

1.给CollectionViewCell添加一个长按手势.


private lazy var collectionView: UICollectionView = {
  let clv = UICollectionView(frame: self.view.frame, collectionViewLayout: ChannelViewLayout())
  clv.backgroundColor = UIColor.white
  clv.delegate = self
  clv.dataSource = self
  clv.register(ChannelViewCell.self, forCellWithReuseIdentifier: ChannelViewCellIdentifier)
  clv.register(ChannelHeaderView.self, forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: ChannelViewHeaderIdentifier)
  let longPress = UILongPressGestureRecognizer(target: self, action: #selector(longPressGesture(_:)))
  clv.addGestureRecognizer(longPress)
  return clv
 }()

2.开始长按时对cell进行截图或拷贝一个cell,并隐藏cell.


 //MARK: - 长按开始
 private func dragBegan(point: CGPoint) {
  indexPath = collectionView.indexPathForItem(at: point)
  if indexPath == nil || (indexPath?.section)! > 0 || indexPath?.item == 0
  {return}
  let item = collectionView.cellForItem(at: indexPath!) as? ChannelViewCell
  item?.isHidden = true
  dragingItem.isHidden = false
  dragingItem.frame = (item?.frame)!
  dragingItem.text = item!.text
  //放大效果(此处可以根据需求随意修改)
  dragingItem.transform = CGAffineTransform(scaleX: 1.1, y: 1.1)
 }

3.在手势移动的时候,找到目标是的indexPatch,再调用系统的api交换这个cell和隐藏cell的位置,并且更新数据.


 //MARK: - 移动过程
 private func drageChanged(point: CGPoint) {
  if indexPath == nil || (indexPath?.section)! > 0 || indexPath?.item == 0 {return}
  dragingItem.center = point
  targetIndexPath = collectionView.indexPathForItem(at: point)
  if targetIndexPath == nil || (targetIndexPath?.section)! > 0 || indexPath == targetIndexPath || targetIndexPath?.item == 0 {return}
  // 更新数据
  let obj = selectedArr[indexPath!.item]
  selectedArr.remove(at: indexPath!.row)
  selectedArr.insert(obj, at: targetIndexPath!.item)
  //交换位置
  collectionView.moveItem(at: indexPath!, to: targetIndexPath!)
  //进行记录
  indexPath = targetIndexPath
 }

4.手势停止或取消时,移除view,显示隐藏cell. (这里手势取消也要掉用此方法)


//MARK: - 长按结束或取消
 private func drageEnded(point: CGPoint) {
  if indexPath == nil || (indexPath?.section)! > 0 || indexPath?.item == 0 {return}
  let endCell = collectionView.cellForItem(at: indexPath!)
  UIView.animate(withDuration: 0.25, animations: {
   self.dragingItem.transform = CGAffineTransform.identity
   self.dragingItem.center = (endCell?.center)!
  }, completion: {
   (finish) -> () in
   endCell?.isHidden = false
   self.dragingItem.isHidden = true
   self.indexPath = nil
  })
 }