2010-12-23 85 views
4

我想創建一個程序,用戶可以通過使用UIPanGestureRecognizer在屏幕上拖動UIImageView。我嘗試了幾種不同的方法,但無法弄清楚。我不確定是否需要創建發件人/請求者。我的理解是,UIImageView需要放在可以處理手勢的UIView中。在我的程序中,我有一個視圖控制器 - AdvancedViewController1。我創建了一個名爲AdvancedView1的UIView。在界面生成器中,我已將AdvancedView1插入AdvancedViewController 1.以下是我的.h.m控制器和視圖文件。我只包括相關的代碼。請讓我知道我是否接近,以及如何修復我的代碼。在此先感謝您的幫助。無法使用UIPanGestureRecognizer移動UIImageView

AdvancedViewController1.h 
#import <UIKit/UIKit.h> 
#import "AdvancedView1.h" 
@interface AdvancedViewController1 : UIViewController { 
UIWindow *window; 
AdvancedView1 *advancedView1; 
UIImageView * option1; 
} 
@property (retain) IBOutlet AdvancedView1 *advancedView1; 
@property (retain) IBOutlet UIImageView *option1; 
@end 

在IB我已經掛一個IBOutlet到AdvancedView1到的UIView和選項1對,我希望能夠以移動的UIImageView。

AdvancedViewController.m 

#import "AdvancedViewController1.h" 
#import "AdvancedView1.h" 
@implementation AdvancedViewController1 
@synthesize advancedView1; 
@synthesize option1 

- (void)viewDidLoad { 
UIGestureRecognizer *pangr = [[UIPanGestureRecognizer alloc]  initWithTarget:self.advancedView1 action:@selector(pan:)]; 
pangr.delegate = self; 
[self.advancedView1 addGestureRecognizer:pangr]; 
[pangr release];  
[super viewDidLoad]; 
} 

AdvancedView1.h 

#import <UIKit/UIKit.h> 
#import "AdvancedViewController1.h" 
@class AdvancedView1; 
@interface AdvancedView1 : UIView{ 
CGPoint* origin; 
} 
@property (nonatomic) CGPoint* origin; 
@end 

AdvancedView1.m 
#import "AdvancedView1.h" 
#import "AdvancedViewController1.h" 
@implementation AdvancedView1; 
@synthesize origin; 

- (void)pan:(UIPanGestureRecognizer *) gesture 
{ 
if ((gesture.state == UIGestureRecognizerStateChanged) || 
(gesture.state == UIGestureRecognizerStateEnded)) { 

CGPoint translation = [gesture translationInView:self]; 
gesture.origin = CGPointMake(gesture.origin.x+translation.x,  gesture.origin.y+translation.y); 
[gesture setTranslation:CGPointZero inView:self]; 
} 

回答

12

你必須在你的pan:選擇器中實際設置UIView的位置。既然你在AdvancedView類中做了它,而不是在它之外,你必須得到視圖的父視圖([self superview]),因爲更新位置是相對於父視圖(包含)。試試這個:

- (void)pan:(UIPanGestureRecognizer *)gesture 
{ 
    if ((gesture.state == UIGestureRecognizerStateChanged) || 
     (gesture.state == UIGestureRecognizerStateEnded)) { 

    CGPoint location = [gesture locationInView:[self superview]]; 

    [self setCenter:location]; 
    } 
} 

請記住,你需要確保你的子類視圖使用戶交互,手勢識別器將無法正常工作。只需在初始化視圖時用[self setUserInteractionEnabled:YES]開啓它即可。

+0

謝謝你的迴應。它正在接近,但我有幾個問題。 UIView現在在觸摸時平移,但是一旦我結束平移手勢,視圖就會消失。任何想法爲什麼?此外,我正在嘗試做的事情是允許UIView內的UIImageView移動,但現在使用此代碼,整個UIView正在移動。這可能嗎?還是我需要創建幾個UIViews並把每個圖像放在一起,這樣我可以移動每個圖像? – JulianF 2010-12-23 23:53:57