我在一個小型項目中嘗試使用更方便的UIPanGestureRecognizer進行拖拽捕捉。希望它可以解決您的問題,如果您需要更多信息,請發表評論(您可以從https://github.com/codedad/SO_Drag_n_Snap_iOS下載GitHub項目)。
我ViewController.h:
@interface ViewController : UIViewController <UIGestureRecognizerDelegate> {
CGPoint firstPos;
}
@property IBOutlet UIImageView *spot1;
@property IBOutlet UIImageView *spot2;
@property IBOutlet UIImageView *bkgr;
@property IBOutlet UIImageView *dragimg;
- (float) distanceSquared:(CGPoint) p1 p2:(CGPoint) p2;
- (IBAction)pan:(UIPanGestureRecognizer *)gesture;
我ViewController.m:
- (float) distanceSquared:(CGPoint) p1 p2:(CGPoint) p2 {
float dx = (p1.x-p2.x);
float dy = (p1.y-p2.y);
return dx*dx+dy*dy;
}
void sort(int*a,int n,int*ndx) {
int*b,*c,t;
int*bi,*ci,ti;
for(b=a+n,bi=ndx+n ; --b>a;) {
--bi;
for(c=b,ci=bi;--c>=a;) {
--ci;
if(*c>*b)t=*b,*b=*c,*c=t,ti=*bi,*bi=*ci,*ci=ti;
}
}
}
- (IBAction)pan:(UIPanGestureRecognizer *)gesture {
CGPoint translatedPoint = [gesture translationInView:self.view];
if ([gesture state] == UIGestureRecognizerStateBegan) {
firstPos = [[gesture view] center];
}
translatedPoint = CGPointMake(firstPos.x+translatedPoint.x, firstPos.y+translatedPoint.y);
[[gesture view] setCenter:translatedPoint];
if ([gesture state] == UIGestureRecognizerStateEnded) {
CGPoint snapPos;
int distances[3];
distances[0] = [self distanceSquared:dragimg.center p2:spot1.center];
distances[1] = [self distanceSquared:dragimg.center p2:spot2.center];
distances[2] = [self distanceSquared:dragimg.center p2:bkgr.center];
int distances_ndx[3] = {0,1,2};
sort(distances, 3, distances_ndx);
switch (distances_ndx[0]) {
case 0:
snapPos = spot1.center;
break;
case 1:
snapPos = spot2.center;
break;
default:
snapPos = bkgr.center;
break;
}
[UIView beginAnimations:nil context:NULL];
[UIView setAnimationDuration:0.2];
[UIView setAnimationCurve:UIViewAnimationCurveEaseOut];
[UIView setAnimationDelegate:self];
dragimg.center = snapPos;
[UIView commitAnimations];
}
}
我ViewController.xib:
我包括4周的UIImageViews。其中3個是靜態的(spot1,2和「家庭」現場背景半色調圈),再加上「家」場內的可拖動的黃色圓圈。我還添加了一個平移手勢識別器。然後我設置的出口:
- 的UIImageViews是連接到spot1,spot2,bkgr和dragimg
- 平移姿勢的委託連接到視圖,動作連接到「PAN」方法
- dragimg的gestureRecognizer然後連接到潘姿勢識別(通過拖動之前加入到ViewController)
來源
2013-05-20 22:18:57
nzs
這裏的問題到底是什麼?如何管理拖動,如何檢測位置是否在反應堆上,或如何做緩慢的動搖?或所有這些? – nzs
非常好的問題。是的,我知道如何拖動UImageView,但是如何將它合併回來?所以是的,所有這些。 –
試試這個http://stackoverflow.com/questions/8658114/iphone-app-implementation-of-drag-and-drop-images-in-uiview –