0

I'm trying to create a draggable image, but i'm trying to confine it's dragging to within a small square rather than the full screen. Could someone tell me where i'm going wrong?. I've placed the code that I have so far below:

-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event{
    UITouch *touch = [[event allTouches] anyObject];
    if([touch view] == dot) {
        CGPoint location = [touch locationInView:self.view];
        dot.center = location;
        if (location.x >10) {
            location.x =10;
        } else if (location.x <10) {
            location.x = 10;
        }
        if (location.y >20) {
            location.y =20;
        } else if (location.y < 20) {
            location.y = 20;
        }      
    }
}
4

2 に答える 2

3

You are assigning location before you are making changes to it.

Apply your limits to location first then assign it to dot.

Also, your limits you are showing would lock your position to 10,20 since you are not allowing it to be more than 10 or less than 10. Likewise with 20.

-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event{
    UITouch *touch = [[event allTouches] anyObject];
    if([touch view] == dot) {
        CGPoint location = [touch locationInView:self.view];
        location.x = MIN(MAX(location.x, 0),10);
        location.y = MIN(MAX(location.y, 0),20);
        dot.center = location;     
    }
}
于 2012-06-15T14:54:55.727 に答える
1

最近こういう画像ドラッグ機能を実装しました。PANジェスチャを使用して画像を移動すると、2つのCGFloat「endPointXとendPointY」が生成されます。「StayonScreenCheck」と「EndStayonScreen check」のコメントの間の以下のコードで、これらが画面に表示されているかどうかを確認します。そうでない場合は、画像が画面から移動しないように調整します。

それがお役に立てば幸いです。画面全体のごく一部で画像を移動したい場合は、画像をホルダーサブビューに追加し、代わりに上のホルダービュー.bounds.size.width/heightを確認します。

CGFloat endPointX = translatedPoint.x + (.35*[(UIPanGestureRecognizer*)sender 
velocityInView:self.view].x);

CGFloat endPointY = translatedPoint.y + (.35*[(UIPanGestureRecognizer*)sender velocityInView:self.view].y);

// Stay on the screen check

if(endPointX < 0) {

    endPointX = 0;

} else if(endPointX > self.view.bounds.size.width) { 

    endPointX = self.view.bounds.size.width;            

}

if(endPointY < 0) {

    endPointY = 0;

} else if(endPointY > self.view.bounds.size.height) {               

    endPointY = self.view.bounds.size.height; 

}

// End of the Stay on Screen check

[UIView beginAnimations:nil context:NULL];

[UIView setAnimationDuration:.35];

[UIView setAnimationCurve:UIViewAnimationCurveEaseOut];

[[sender view] setCenter:CGPointMake(endPointX, endPointY)];

[UIView commitAnimations];
于 2012-06-15T14:49:24.577 に答える