-(void)addLongPressGesture{UILongPressGestureRecognizer*longPress=[[UILongPressGestureRecognizeralloc]initWithTarget:selfaction:@selector(longPressGestureRecognized:)];[self.tableViewaddGestureRecognizer:longPress];}-(void)longPressGestureRecognized:(UILongPressGestureRecognizer*)longPress{// 关键点:通过长按手势获取点击位置,进而获取到对应的indexPath,从而操作对应的cellCGPointlocation=[longPresslocationInView:self.tableView];NSIndexPath*indexPath=[self.tableViewindexPathForRowAtPoint:location];staticUIView*snapshot=nil;staticNSIndexPath*sourceIndexPath=nil;UIGestureRecognizerStatestate=longPress.state;switch(state){caseUIGestureRecognizerStateBegan:{if(indexPath){// 移动开始时,截取对应的cell的snapshot,隐藏对应的cellsourceIndexPath=indexPath;UITableViewCell*cell=[self.tableViewcellForRowAtIndexPath:indexPath];snapshot=[selfcustomSnapshotFromView:cell];__blockCGPointcenter=cell.center;snapshot.center=center;snapshot.alpha=0;[self.tableViewaddSubview:snapshot];[UIViewanimateWithDuration:0.25animations:^{center.y=location.y;snapshot.center=center;snapshot.transform=CGAffineTransformMakeScale(1.05,1.05);snapshot.alpha=0.98;cell.alpha=0;cell.hidden=YES;}];}break;}caseUIGestureRecognizerStateChanged:{// 移动时,不断修改snapshot的位置,并交换数据和cellCGPointcenter=snapshot.center;center.y=location.y;snapshot.center=center;if(indexPath&&![indexPathisEqual:sourceIndexPath]){[self.dataSourceexchangeObjectAtIndex:indexPath.rowwithObjectAtIndex:sourceIndexPath.row];[self.tableViewmoveRowAtIndexPath:sourceIndexPathtoIndexPath:indexPath];sourceIndexPath=indexPath;}break;}default:{// 移动完成后,显示被移动的cell,移除snapshotUITableViewCell*cell=[self.tableViewcellForRowAtIndexPath:sourceIndexPath];cell.alpha=0;[UIViewanimateWithDuration:0.25animations:^{snapshot.center=cell.center;snapshot.transform=CGAffineTransformIdentity;snapshot.alpha=0.0;cell.alpha=1.0;}completion:^(BOOLfinished){cell.hidden=NO;sourceIndexPath=nil;[snapshotremoveFromSuperview];snapshot=nil;}];break;}}}-(UIView*)customSnapshotFromView:(UIView*)inputView{// Make an image from the input view.UIGraphicsBeginImageContextWithOptions(inputView.bounds.size,NO,0);[inputView.layerrenderInContext:UIGraphicsGetCurrentContext()];UIImage*image=UIGraphicsGetImageFromCurrentImageContext();UIGraphicsEndImageContext();// Create an image view.UIView*snapshot=[[UIImageViewalloc]initWithImage:image];snapshot.layer.masksToBounds=NO;snapshot.layer.cornerRadius=0.0;snapshot.layer.shadowOffset=CGSizeMake(-5.0,0.0);snapshot.layer.shadowRadius=5.0;snapshot.layer.shadowOpacity=0.4;returnsnapshot;}