I have a small imageView that moves on the screen using the UIPanGestureRecognizer
, but when it comes out from the edges of the superview does not get more touches and therefore can no longer turn back. How can I prevent that the image comes out from the edges of the superview? This is the code:
- (void)pan:(UIPanGestureRecognizer *)gestureRecognizer
{
if (inLongPress) {
UIView *hitView = [gestureRecognizer view];
[self adjustAnchorPointForGestureRecognizer:gestureRecognizer];
if (!(CGRectContainsRect(self.imageView.frame, hitView.frame))) {
[UIView beginAnimations:@"" context:NULL];
[hitView setCenter:CGPointMake(_prevCenter.x, _prevCenter.y)];
[UIView commitAnimations];
}
_prevCenter=hitView.center;
if ([gestureRecognizer state] == UIGestureRecognizerStateBegan || [gestureRecognizer state] == UIGestureRecognizerStateChanged) {
CGPoint translation = [gestureRecognizer translationInView:[hitView superview]];
[hitView setCenter:CGPointMake([hitView center].x + translation.x, [hitView center].y + translation.y)];
[gestureRecognizer setTranslation:CGPointZero inView:[hitView superview]];
}
if ([gestureRecognizer state] == UIGestureRecognizerStateEnded){
inLongPress=NO;
hitView.alpha=1.0;
}
}
}
在视图控制器的viewDidLoad方法中,只需将superview的clipsToBounds属性设置为YES即可 。
[superview setClipsToBounds:YES];
just use a couple of if
that limit the CGPoint to an allowed range.
Something like this makes sure that you can't move the object outside of the view:
CGFloat proposedX = location.x;
CGFloat proposedY = location.y;
CGRect objectFrame = hitView.frame;
CGFloat allowedXMin = 0 + objectFrame.size.width / 2.0f;
CGFloat allowedXMax = self.view.bounds.size.width - objectFrame.size.width / 2.0f;
CGFloat allowedYMin = 0 + objectFrame.size.height / 2.0f;
CGFloat allowedYMax = self.view.bounds.size.height - objectFrame.size.height / 2.0f;
if (proposedX < allowedXMin) {
proposedX = allowedXMin;
}
else if (proposedX > allowedXMax) {
proposedX = allowedXMax;
}
if (proposedY < allowedYMin) {
proposedY = allowedYMin;
}
else if (proposedY > allowedYMax) {
proposedY = allowedYMax;
}
location = CGPointMake(proposedX, proposedY);
hitView.center = location;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.