关于tableview的移动,apple提供了官方的做法,但是无法做扩展,生成的cell往往不符合实际需求,所以这里提供自定义移动操作:
//为tableview添加对应的手势来模拟移动手势。
UILongPressGestureRecognizer* longPressGesture=[[UILongPressGestureRecognizer alloc]initWithTarget:self action:@selector(handlerLongPress:)];
longPressGesture.minimumPressDuration=0.5;
[_sortTableView addGestureRecognizer:longPressGesture];
-(void)handlerLongPress:(UILongPressGestureRecognizer*)sender{
switch (sender.state) {
case UIGestureRecognizerStateBegan:
[self handlerLongPressBegan:sender];
break;
case UIGestureRecognizerStateChanged:
[self handlerLongPressChanged:sender];
break;
case UIGestureRecognizerStateCancelled:
[self handlerLongPressEnded:sender];
break;
case UIGestureRecognizerStateEnded:
[self handlerLongPressEnded:sender];
break;
default:
break;
}
}
-(void)handlerLongPressBegan:(UILongPressGestureRecognizer*)longPressGesture{
//手势识别开始阶段获取对应的触碰位置.
CGPoint location=[longPressGesture locationInView:_sortTableView];
NSIndexPath* indexPath=[_sortTableView indexPathForRowAtPoint:location];
//判断触碰位置是否为tableview的某一行
if(indexPath){
//_sourceIndexPath为属性变量用于保存初始被移动的cell的位置。
_sourceIndexPath=indexPath;
//获取cell
QTShortcutsListenSortTableCell* cell=[_sortTableView cellForRowAtIndexPath:indexPath];
//对cell进行截图并保存到属性变量
_snapshot=[cell resizableSnapshotViewFromRect:CGRectMake(0, 0, cell.frame.size.width, 50) afterScreenUpdates:NO withCapInsets:UIEdgeInsetsZero];
//得到初始位置的cell的中心。然后隐藏cell,并将截图放到cell对应的位置,用此截图来假装一个cell来拖动。
CGPoint center=cell.center;
[_sortTableView addSubview:_snapshot];
center.y=location.y;
_snapshot.center=center;
_snapshot.transform=CGAffineTransformMakeScale(1, 1);
_snapshot.alpha=1;
_snapshot.backgroundColor=cell.backgroundColor;
cell.backgroundColor=[UIColor clearColor];
cell.hidden=true;
}
}
-(void)handlerLongPressChanged:(UILongPressGestureRecognizer*)longPressGesture{
//当手势改变的时候,获取所处的位置,然后一步步交换截图以及对应的cell和相对应的数据。
CGPoint location=[longPressGesture locationInView:_sortTableView];
NSIndexPath* indexPath=[_sortTableView indexPathForRowAtPoint:location];
CGPoint center=_snapshot.center;
center.y=location.y;
_snapshot.center=center;
if(indexPath&&![indexPath isEqual:_sourceIndexPath]){
//这里的_sortModelArr对应着数据模型数组
QTShortcutsListenSortModel* modelToMove=_sortModelArr[_sourceIndexPath.row];
[_sortModelArr removeObjectAtIndex:_sourceIndexPath.row];
[_sortModelArr insertObject:modelToMove atIndex:indexPath.row];
[_sortTableView moveRowAtIndexPath:_sourceIndexPath toIndexPath:indexPath];
_sourceIndexPath=indexPath;
}
}
-(void)handlerLongPressEnded:(UILongPressGestureRecognizer*)longPressGesture{
QTShortcutsListenSortTableCell* cell=[_sortTableView cellForRowAtIndexPath:_sourceIndexPath];
//手势结束以后,将截图置为nil,将原来的cell展示出来。
[UIView animateWithDuration:0.25 animations:^{
_snapshot.center=cell.center;
_snapshot.transform=CGAffineTransformIdentity;
_snapshot.alpha=0;
cell.backgroundColor=_snapshot.backgroundColor;
cell.hidden=false;
} completion:^(BOOL finished) {
[_snapshot removeFromSuperview];
_snapshot=nil;
}];
_sourceIndexPath=nil;
}