實作控制項拖曳有多種方式,最省事的是直接用 UICollectionView 的代理方法。但實務上常見的狀況是:頁面一開始用普通按鈕排出九宮格,後來才收到「要能長按拖曳排序」的需求,又不想推翻既有佈局。這種時候該怎麼辦?
做法其實不複雜:用 UILongPressGestureRecognizer 搭配位置判斷即可。
@interface YRViewController ()
{
BOOL contain; // 目前是否停在別的按鈕上
CGPoint startPoint; // 長按起點
CGPoint originPoint; // 拖曳中這個按鈕「原本該在」的位置
}
@property (strong, nonatomic) NSMutableArray *itemArray;
@end
- (void)viewDidLoad
{
[super viewDidLoad];
for (NSInteger i = 0; i < 8; i++) {
UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
btn.backgroundColor = [UIColor redColor];
btn.frame = CGRectMake(50 + (i % 2) * 100, 64 + (i / 2) * 100, 90, 90);
btn.tag = i;
btn.titleLabel.font = [UIFont boldSystemFontOfSize:20];
[btn setTitle:[NSString stringWithFormat:@"%d", (int)(1 + i)]
forState:UIControlStateNormal];
[self.view addSubview:btn];
UILongPressGestureRecognizer *longGesture =
[[UILongPressGestureRecognizer alloc] initWithTarget:self
action:@selector(buttonLongPressed:)];
[btn addGestureRecognizer:longGesture];
[self.itemArray addObject:btn];
}
}
思路是這樣的:拖動的那顆按鈕跟著手指走,走到別的按鈕位置上時,兩者交換位置。分三個階段處理:
- (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);
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; // 沒有落在別人身上,就歸位
}
}];
}
}
這個方法檢查被拖曳按鈕的中心點,是否落在 itemArray 中其他元素的範圍內;若在,回傳該元素在陣列中的索引,否則回傳 -1。
- (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;
}
就這樣,靠著位置判斷完成控制項的交換與重排。若要進一步持久化這個順序,可以在手勢結束時把 itemArray 的順序寫入模型並存檔。