公司项目需要改一个按钮拖动排序模块,于是就自己写了一个,以为代码会很多,起始很少就实现,主要运用了长按手势,recognizer.state==UIGestureRecognizerStateChanged时判断选中按钮最后悬停的位置,然后依次改动起始位置到最后悬停位置的按钮的frame即可
- (void)longPress:(UILongPressGestureRecognizer*)recognizer
{
//NSLog(@"此方法在拖拽过程中会一直调用");
UIButton*selectedBtn = (UIButton*)recognizer.view;
CGPointlocation = [recognizerlocationInView:self.view];
if(recognizer.state==UIGestureRecognizerStateBegan) {
[UIViewanimateWithDuration:0.2animations:^{
selectedBtn.transform=CGAffineTransformMakeScale(1.2,1.2);
selectedBtn.alpha=0.5;
}];
//记录被拖拽按钮的当前位置
_valuePoint= selectedBtn.center;
}elseif(recognizer.state==UIGestureRecognizerStateChanged) {
selectedBtn.center= location;
for(UIButton*buttoninself.view.subviews) {
if(CGRectContainsPoint(button.frame, selectedBtn.center) && button != selectedBtn) {
NSIntegerfromIndex = selectedBtn.tag-_baseTag;
NSIntegertoIndex = button.tag-_baseTag;
NSLog(@"开始位置=%ld结束位置=%ld",fromIndex,toIndex);
//向后拖动
if(toIndex > fromIndex) {
[UIViewanimateWithDuration:0.2animations:^{
for(NSIntegeri = fromIndex +1; i <= toIndex; i++) {
UIButton*button = (UIButton*)[self.viewviewWithTag:i +_baseTag];
_nextPoint= button.center;
button.center=_valuePoint;
_valuePoint=_nextPoint;
button.tag--;
[buttonsetTitle:[NSStringstringWithFormat:@"第%ld个",button.tag-_baseTag]forState:UIControlStateNormal];
}
selectedBtn.tag=_baseTag+ toIndex;
}];
//向前拖动
}else{
[UIViewanimateWithDuration:0.2animations:^{
for(NSIntegeri = fromIndex -1; i >= toIndex; i--) {
UIButton*button = (UIButton*)[self.viewviewWithTag:i +_baseTag];
_nextPoint= button.center;
button.center=_valuePoint;
_valuePoint=_nextPoint;
button.tag++;
}
selectedBtn.tag=_baseTag+ toIndex;
[buttonsetTitle:[NSStringstringWithFormat:@"第%ld个",button.tag-_baseTag]forState:UIControlStateNormal];
}];
}
}
}
}elseif(recognizer.state==UIGestureRecognizerStateEnded) {
[UIViewanimateWithDuration:0.2animations:^{
selectedBtn.transform=CGAffineTransformIdentity;
selectedBtn.alpha=1.0;
selectedBtn.center=_valuePoint;
[selectedBtnsetTitle:[NSStringstringWithFormat:@"第%ld个",selectedBtn.tag-_baseTag]forState:UIControlStateNormal];
}];
}
}