2011-07-18 6 views
0

これは私のコードです:私は何をしたいかiphone :: touchesMoved:UIImageViewをUIView内に移動しますか?

- (void) touchesBegan: (NSSet *)touches withEvent: (UIEvent *)event { 

CGPoint pt = [[touches anyObject] locationInView:self.view]; 
startLocation = pt; 
[super touchesBegan: touches withEvent: event]; 
} 

-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event { 
CGPoint pt = [[touches anyObject] locationInView:self.view]; 
CGRect frame = [self.view frame]; 
frame.origin.x += pt.x - startLocation.x; 
frame.origin.y += pt.y - startLocation.y; 
[self.view setFrame:frame]; 
} 


- (void)viewDidLoad 
{ 
[super viewDidLoad]; 

UIView *v = [[UIView alloc] initWithFrame: CGRectMake(0, 0, 100, 100)]; 
v.backgroundColor = [UIColor redColor]; 


UIImageView *imv = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"boo2.png"]]; 
imv.frame = CGRectMake(0, 0, 50, 50); 
[v addSubview:imv]; 

[self.view addSubview: v]; 
[v release]; 

UIView *v2 = [[UIView alloc] initWithFrame: CGRectMake(100, 100, 100, 100)]; 
v2.backgroundColor = [UIColor blueColor]; 


UIImageView *imv2 = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"boo2.png"]]; 
imv2.frame = CGRectMake(0, 0, 50, 50); 
[v2 addSubview:imv2]; 

[self.view addSubview: v2]; 
[v2 release]; 
} 

はUIViewの全体ではなく、ビュー内のUIImageViewを移動することです。しかし、上のコードは、私がドラッグしようとすると、全体のビューを移動します。

注:画像はviewdidloadで宣言されていない他の関数からの戻り値です。 UIImageView変数を宣言できないとします。

答えて

1

私はあなたが何をしようとしているのかよく分かりません。私はUIImageView'sをそれぞれUIViewの中に入れて、なぜView Controllerのビューに入れたのか分かりません。ビューコントローラのビューのサブビューとして直接UIImageView'sを追加することもできます。

しかし、私が作ることができるものは、ユーザーが画面上の画像をドラッグできる必要があるように見えます。

この場合、UIImageView'sの各1つをアレイに格納することをお勧めします。次に、touchesBegan:withEvent:には、どれがUIImageViewがタッチされているかを判断する必要があります。メインビューでの位置を表すCGPointを取得することは、コードの場合と同様に適切です。メインビューのサブビューとしてUIImageView'sを直接追加した場合、このCGPointの座標とUIImageView'sのフレームを比較して、どちらが押されているかを判断できます。

ドラッグを許可するには、タッチの開始時にUIImageViewの座標を保存する必要があります。次に、タッチが動くたびに、UIImageViewの新しいx位置を元のx位置と移動距離として計算することができます。すなわち、y位置用

newImageViewX = imageViewStartX + (newTouchX - touchStartX);

と同様です。

関連する問題