2012-01-11 72 views
0

我想在iphone應用程序中做拖放操作。我有一個包含多層視圖的主視圖。iphone應用程序:拖放UIImageView

我放在:

-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event  

在主視圖,但這不會被調用。當用戶第一次觸摸時,我可以在視圖上加載縮略圖圖像。我嘗試拖動UIImageView,但touchesMoved:未被調用。

這裏是一些代碼:(這是一個被加載當用戶觸摸的視圖,它裝載和放置underneth光標拖動圖像)

[dragImage addTarget:self action:@selector(endDrag) forControlEvents:UIControlEventTouchUpOutside]; 
[dragImage addTarget:self action:@selector(endDrag) forControlEvents:UIControlEventTouchUpInside]; 
[dragImage addTarget:self action:@selector(endDrag) forControlEvents:UIControlEventTouchDragInside]; 
+0

你在哪裏實現'touchesMove:'?請記住它是'UIViewController',而不是'UIView'的一種方法... – Saphrosit 2012-01-11 03:16:26

+0

幫你一個忙,並使用GestureRecognizer – vikingosegundo 2012-01-11 03:19:13

+0

我在ViewController級別有它。事件只有在我離開屏幕後纔會觸發,然後在鼠標關閉時回到屏幕上。我懷疑它與將dragImage.Center = point放在拖拽下的圖像有關。有東西在吃事件,不會冒泡它或什麼東西..如果touchesMove不觸發它可能是好的,如果dragImage觸發DragInside事件。但這並不是觸發 – Arcadian 2012-01-11 03:20:58

回答

1

這是我做拖動的圖像

UIPanGestureRecognizer *panRecognizer = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(move:)]; 
[panRecognizer setMinimumNumberOfTouches:1]; 
[panRecognizer setMaximumNumberOfTouches:1]; 
[panRecognizer setDelegate:self]; 
[imageView_ addGestureRecognizer:panRecognizer]; 

然後:在屏幕上

-(void)move:(id)sender { 

    CGPoint translatedPoint = [(UIPanGestureRecognizer*)sender translationInView:self.view]; 

    if([(UIPanGestureRecognizer*)sender state] == UIGestureRecognizerStateBegan) { 

     firstX = [[sender view] center].x; 
     firstY = [[sender view] center].y; 
    } 

    translatedPoint = CGPointMake(firstX+translatedPoint.x, firstY+translatedPoint.y); 
    [[sender view] setCenter:translatedPoint]; 

} 
+0

[請參閱觸摸此方法的示例代碼](http://developer.apple.com/library/ios/samplecode/Touches/Introduction/Intro.html#//apple_ref/doc/uid/DTS40007435) – vikingosegundo 2012-01-11 03:27:18

+0

我得到與您的代碼相同的結果。我只能在我再次觸摸後才能拖動圖像。我不知道如何最好地解釋它。 – Arcadian 2012-01-11 03:36:24

+0

並且如果您運行示例代碼? – vikingosegundo 2012-01-11 03:46:01

1

你可以做的是insid放置的UIImageView e UIControl(將響應UIControlEventTouchDragInside)。

UIControl *dragImageControl = [[UIControl alloc] initWithFrame:dragImageView.frame]; 
     [dragImageControl addSubview:dragImageView]; 

[self.view addSubview:dragImageControl]; 

[dragImageControl addTarget:self action:@selector(imageTouch:withEvent:) forControlEvents:UIControlEventTouchDown]; 
[dragImageControl addTarget:self action:@selector(imageMoved:withEvent:) forControlEvents:UIControlEventTouchDragInside]; 

和imageMoved,你可以有這樣的代碼:

- (IBAction) imageMoved:(id) sender withEvent:(UIEvent *) event 
{ 
    CGPoint point = [[[event allTouches] anyObject] locationInView:self.view]; 
    UIControl *control = sender; 
    control.center = point; 
}