最近由于系统升级,xcode6.系列版本有bug,所以我开始使用xcode7。用了之后突然想到collectionView在iOS9中发布了一个可以移动单元格的新特性,于是尝试实现,但是看不到api文档接口,只有几列api放在那里。于是在网上搜索,国内没有找到这样的文章,于是FQ继续搜索,终于找到了swift版,于是转成oc版,帮助国内的朋友学习使用。下面是具体的用法:1、创建collectionView并设置代理-(UICollectionView*)collectionView{if(_collectionView==nil){UICollectionViewFlowLayout*layout=[[UICollectionViewFlowLayoutalloc]init];layout.itemSize=CGSizeMake(50,50);_collectionView=[[UICollectionViewalloc]initWithFrame:CGRectMake(0,20,self.view.bounds.size.width,self.view.bounds.size.height)collectionViewLayout:layout];layout.minimumLineSpacing=10;layout.minimumInteritemSpacing=10;[_collectionViewregisterClass:[UICollectionViewCell类]forCellWithReuseIdentifier:@"Cell"];_collectionView.backgroundColor=[UIColor青色];_collectionView.dataSource=self;//这里添加一个长按手势,并通过这个手势触发cell的移动[_collectionViewaddGestureRecognizer:longGesture];}返回rn_collectionView;}2.设置其资源_dataSource=[NSMutableArrayarray];for(inti=1;i<=50;i++){NSString*imageName=[NSStringstringWithFormat:@"%d",i];[_dataSourceaddObject:图像名称];}3。监听手势并设置允许cell移动和资源交换-(void)handlelongGesture:(UILongPressGestureRecognizer*)longGesture{//判断手势状态切换(longGesture.state){caseUIGestureRecognizerStateBegan:{//判断手势的位置是否是在路径上NSIndexPath*indexPath=[self.collectionViewindexPathForItemAtPoint:[longGesturelocationInView:self.collectionView]];如果(indexPath==nil){中断;}//开始移动Cell路径上的item[self.collectionViewbeginInteractiveMovementForItemAtIndexPath:indexPath];}休息;caseUIGestureRecognizerStateChanged://移动过程中随时更新单元格位置[self.collectionViewupdateInteractiveMovementTargetPosition:[longGesturelocationInView:self.collectionView]];休息;caseUIGestureRecognizerStateEnded://移动结束后关闭单元格移动[self.collectionViewendInteractiveMovement];休息;默认值:[self.collectionViewcancelInteractiveMovement];休息;}}-(BOOL)collectionView:(UICollectionView*)collectionViewcanMoveItemAtIndexPath:(NSIndexPath*)indexPath{//返回YES允许其项目移动returnYES;}-(void)collectionView:(UICollectionView*)collectionViewmoveItemAtIndexPath:(NSIndexPath*)sourceIndexPathtoIndexPath:(NSIndexPath*)destinationIndexPath{//取出源项数据idobjc=[_dataSourceobjectAtIndex:sourceIndexPath.item];//从资源数组中取出数据[_dataSourceremoveObject:objc];//插入数据到资源数组中的目标位置[_dataSourceinsertObject:objcatIndex:destinationIndexPath.item];}通过上面的设置,就可以成功移动cell了,下面给出效果图,以便于使用collectionView的新特性完成。如有错误,敬请期待,谢谢!我想你会是我的一切,我正在为此而战,希望这不仅仅是我!
