实现控件拖动的方法有多种,可以使用UICollectionView的代理方法直接实现,但是有些开发者在初始时没有使用UICollectionView创建九宫格,后来增加需求,却要增加这种拖动移动的效果,又不想更改页面的初始控件,那么应该怎么实现呢?
方法很简单,首先在@interface创建以下全局变量;
@interface YRViewController () { BOOL contain; CGPoint startPoint; CGPoint originPoint; } @property (strong , nonatomic) NSMutableArray *itemArray; @end
如图所示,在viewDidLoad里创建了如下的控件布局;
1 - (void)viewDidLoad 2 { 3 [super viewDidLoad]; 4 5 for (NSInteger i = 0;i<8;i++) 6 { 7 UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom]; 8 btn.backgroundColor = [UIColor redColor]; 9 btn.frame = CGRectMake(50+(i%2)*100, 64+(i/2)*100, 90, 90); 10 btn.tag = i; 11 btn.titleLabel.font = [UIFont boldSystemFontOfSize:20]; 12 [btn setTitle:[NSString stringWithFormat:@"%d",1+i] forState:UIControlStateNormal]; 13 [self.view addSubview:btn]; 14 UILongPressGestureRecognizer *longGesture = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(buttonLongPressed:)]; 15 [btn addGestureRecognizer:longGesture]; 16 [self.itemArray addObject:btn]; 17 18 } 19 }
下面,我们就要思考,如何实现长按移动了,控件的移动并且重新排序,主要是考虑移动的那个控件移动到新的位置,直接看下列代码,
class="brush:objc;gutter:true;">- (void)buttonLongPressed:(UILongPressGestureRecognizer *)sender { UIButton *btn = (UIButton *)sender.view; if (sender.state == UIGestureRecognizerStateBegan) { startPoint = [sender locationInView:sender.view]; originPoint = btn.center; [UIView animateWithDuration:Duration animations:^{ btn.transform = CGAffineTransformMakeScale(1.1, 1.1); btn.alpha = 0.7; }]; } else if (sender.state == UIGestureRecognizerStateChanged) { CGPoint newPoint = [sender locationInView:sender.view]; CGFloat deltaX = newPoint.x-startPoint.x; CGFloat deltaY = newPoint.y-startPoint.y; btn.center = CGPointMake(btn.center.x+deltaX,btn.center.y+deltaY); //NSLog(@"center = %@",NSStringFromCGPoint(btn.center)); NSInteger index = [self indexOfPoint:btn.center withButton:btn]; if (index<0) { contain = NO; } else { [UIView animateWithDuration:Duration animations:^{ CGPoint temp = CGPointZero; UIButton *button = _itemArray[index]; temp = button.center; button.center = originPoint; btn.center = temp; originPoint = btn.center; contain = YES; }]; } } else if (sender.state == UIGestureRecognizerStateEnded) { [UIView animateWithDuration:Duration animations:^{ btn.transform = CGAffineTransformIdentity; btn.alpha = 1.0; if (!contain) { btn.center = originPoint; } }]; } } - (NSInteger)indexOfPoint:(CGPoint)point withButton:(UIButton *)btn { for (NSInteger i = 0;i<_itemArray.count;i++) { UIButton *button = _itemArray[i]; if (button != btn) { if (CGRectContainsPoint(button.frame, point)) { return i; } } } return -1; }
这样,我们通过位置判断的方式,让控件得以重新排列。