点击移动
collectionView的点击方法,我这里分为两段,第一段为点击处理事件,第二段为点击添加添加标签(编辑状态下第一段可以点击排序)
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
if indexPath.section > 0 {
// 更新数据
let obj = recommendArr[indexPath.item]
recommendArr.remove(at: indexPath.item)
selectedArr.append(obj)
//移动方法
collectionView.moveItem(at: indexPath, to: NSIndexPath(item: selectedArr.count - 1, section: 0) as IndexPath)
} else {
if isEdite {
if indexPath.item == 0 {return}
// 更新数据
let obj = selectedArr[indexPath.item]
selectedArr.remove(at: indexPath.item)
recommendArr.insert(obj, at: 0)
//移动方法
collectionView.moveItem(at: indexPath, to: NSIndexPath(item: 0, section: 1) as IndexPath)
} else {
if switchoverCallback != nil {
//处理点击的闭包
switchoverCallback!(selectedArr, recommendArr, indexPath.item)
_ = navigationController?.popViewController(animated: true)
}
}
}
}
其他
此代码只是一个效果,没有怎么封装,如果仔细看过的朋友可以知道其实没有多么复杂
点击移动
collectionView.moveItem(at: indexPath, to: NSIndexPath(item: 0, section: 1) as IndexPath)
拖拽移动
collectionView.moveItem(at: indexPath!, to: targetIndexPath!)
主要就是这两个方法,其他都是处理逻辑以及视图效果.
提示
如果你们是从iOS9开始适配的话,那么可以用系统的Api,非常简单好用,大家这里可以自己去试试.
// Support for reordering
@available(iOS 9.0, *)
open func beginInteractiveMovementForItem(at indexPath: IndexPath) -> Bool // returns NO if reordering was prevented from beginning - otherwise YES
@available(iOS 9.0, *)
open func updateInteractiveMovementTargetPosition(_ targetPosition: CGPoint)
@available(iOS 9.0, *)
open func endInteractiveMovement()
@available(iOS 9.0, *)
open func cancelInteractiveMovement()
源码可以从这里下载
以上所述是小编给大家介绍的Swift下使用UICollectionView 实现长按拖拽功能,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对ASPKU网站的支持!
注:相关教程知识阅读请移步到swift教程频道。








