2012-02-24 1 views
0

イメージビューをドラッグしようとしています。私はそうすることで少しの成功を収めましたが、私が望むように行動していません。私はそれがイメージの中に触れてそれをドラッグする場合にのみ移動することを望む。 しかし、画面上のどこからでも触れてドラッグしても動いています。イメージビューをドラッグする

私はこのようなコードを書かれている:

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event 
    { 
     //retrieve touch point 
     CGPoint pt= [[ touches anyObject] locationInView:[self.view.subviews objectAtIndex:0]]; 
     startLocation = pt; 

    } 

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

    CGPoint pt = [[touches anyObject] locationInView: [self.view.subviews objectAtIndex:0]]; 

    CGRect frame = [[self.view.subviews objectAtIndex:0]frame]; 
    frame.origin.x += pt.x - startLocation.x; 
    frame.origin.y += pt.y - startLocation.y; 
    [[self.view.subviews objectAtIndex:0] setFrame: frame]; 

}

+0

を?イメージビューのインスタンスを宣言することができます。そして、CGRectContainsPointを使ってイメージビューに触れているかどうかをチェックします。 – Ilanchezhian

+0

タッチ時にあなたのタッチポイントがあなたのイメージビューにあるかどうかを確認することができます – Bonny

+0

イメージビューのフレームが画面全体をカバーするように設定されていますか? –

答えて

2

をlocationInViewメソッドの戻り値は、ビューのフレームに対してポイントです。最初にビューフレーム内にあるかどうかを確認します。

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event 
{ 
    CGRect targetFrame = [self.view.subviews objectAtIndex:0].frame; 
    //retrieve touch point 
    CGPoint pt= [[ touches anyObject] locationInView:[self.view.subviews objectAtIndex:0]]; 
    //check if the point in the view frame  
    if (pt.x < 0 || pt.x > targetFrame.size.width || pt.y < 0 || pt.y > targetFrame.size.height) 
    { 
     isInTargetFrame = NO; 
    } 
    else 
    { 
     isInTargetFrame = YES; 
     startLocation = pt; 
    } 
} 

- (void) touchesMoved:(NSSet*)touches withEvent:(UIEvent*)event 
{ 
     if(!isInTargetFrame) 
     { 
      return; 
     } 
     //move your view here... 
} 
+0

working.someの変更:frameはプロパティではないので、メッセージとして送信してください。if条件でframeをtargetFrameに置き換えてください。 – condinya

0

このような何か試してください:あなたはsubviews` `でアクセスしているのはなぜ

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event 
{ 
    //retrieve touch point 
    startLocation = [[ touches anyObject] locationInView:self.view]; 
// Now here check to make sure that start location is within the frame of 
// your subview [self.view.subviews objectAtIndex:0] 
// if it is you need to have a property like dragging = YES 
// Then in touches ended you set dragging = NO 

} 

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

CGPoint pt = [[touches anyObject] locationInView: [self.view.subviews objectAtIndex:0]]; 

CGRect frame = [[self.view.subviews objectAtIndex:0]frame]; 
frame.origin.x += pt.x - startLocation.x; 
frame.origin.y += pt.y - startLocation.y; 
[[self.view.subviews objectAtIndex:0] setFrame: frame]; 
関連する問題