2012-11-12 66 views
6

我正在學習iOS,我無法找到如何將拖放行爲添加到UIView簡單的拖放視圖?

我想:

[_view addTarget:self action:@selector(moved:withEvent:) forControlEvents:UIControlEventTouchDragInside]; 

它說:「爲UIView沒有可見的接口聲明選擇addTarget (etc)

我也嘗試添加一個平移手勢識別,但不知道這是什麼,我需要

- (IBAction)test:(id)sender { 
     NSLog(@"dfsdfsf"); 
    } 

它被稱爲,但不知道如何獲得事件的座標。 iOS中註冊移動事件的回調/拖放操作的標準,簡單的方法是什麼?

在此先感謝。

回答

12

A UIPanGestureRecognizer絕對是要走的路。如果你希望用戶拖動的觀點,你需要的手勢的「翻譯」(運動)SuperView把座標系中:

- (IBAction)panWasRecognized:(UIPanGestureRecognizer *)recognizer { 
    CGPoint translation = [recognizer translationInView:_view.superview]; 

一旦你的翻譯,你可以移動(「拖動「)通過改變鑑於其center

CGPoint center = _view.center; 
    center.x += translation.x; 
    center.y += translation.y; 
    _view.center = center; 

最後,你要設置的移動手勢識別器的翻譯回零,所以,下一次你得到的消息,它只是告訴你的手勢多少感動自上次信息:

[recognizer setTranslation:CGPointZero inView:_view.superview]; 
} 

這是一起容易複製/粘貼:

- (IBAction)panWasRecognized:(UIPanGestureRecognizer *)recognizer { 
    CGPoint translation = [recognizer translationInView:_view.superview]; 

    CGPoint center = _view.center; 
    center.x += translation.x; 
    center.y += translation.y; 
    _view.center = center; 

    [recognizer setTranslation:CGPointZero inView:_view.superview]; 
} 
+0

用戶必須在viewDidLoad中添加此: UIPanGestureRecognizer *聲像= [[UIPanGestureRecognizer頁頭] initWithTarget:自我行動:@selector(panWasRecognized: )]; [_viewaddGestureRecognizer:panner]; –

+1

或者您可以在故事板或XIB中添加手勢識別器。 –

+0

這是正確的,但當我跟着你的答案我不知道它需要,所以它不適用於我:D –

4

開始於touchesBegan,touchesMoved,touchesEnded。在你的UIView子類中重寫這些,你將會學習事件系統。你可以得到像這樣的事件座標:

- (void) touchesBegan:(NSSet *) touches withEvent:(UIEvent *) event 
{ 
    float x = [[touches anyObject] locationInView:self].x; 
    float y = [[touches anyObject] locationInView:self].y; 
} 

然後有很多東西可以在不同的視圖之間轉換座標等等。一旦你瞭解了這一點,你就可以使用你已經找到的UIGestureRecognizer東西,這就是你需要的東西。

您將需要一個平移手勢識別器來進行拖放操作。您可以在UIPanGestureRecognizer中使用locationInView:選擇器來查找您在任何給定時刻的位置。

你把你的手勢識別,像這樣,不與目標 - 動作的東西你想:

UIPanGestureRecognizer *dragDropRecog = [[UIPanGestureRecognizer alloc] initWithTarget:yourView action:@selector(thingDragged:)]; 
[yourView addGestureRecognizer:dragDropRecog]; 

然後你有你的觀點,以實現選擇thingDragged:

- (void) thingDragged:(UIPanGestureRecognizer *) gesture 
{ 
    CGPoint location = [gesture locationInView:self]; 
    if ([gesture state] == UIGestureRecognizerStateBegan) { 
     // Drag started 
    } else if ([gesture state] == UIGestureRecognizerStateChanged) { 
     // Drag moved 
    } else if ([gesture state] == UIGestureRecognizerStateEnded) { 
     // Drag completed 
    } 
} 

你將轉換正在拖動的視圖,並處理結束部分的拖放。