iOS如何?長按拖動控制項,ios拖動控制項
實現控制項拖動的方法有多種,可以使用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 }
下面,我們就要思考,如何?長按移動了,控制項的移動並且重新排序,主要是考慮移動的那個控制項移動到新的位置,直接看下列代碼,
- (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;}
這樣,我們通過位置判斷的方式,讓控制項得以重新排列。