如何通过Pan手势限制可移动视图 [英] How to restrict a moveable view by Pan gesture
问题描述
我有一个 UIImageView
,它可通过平移手势移动。
I have a UIImageView
which is moveable via a pan gesture.
UIPanGestureRecognizer *pan = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(handlePan:)];
[self.photoMask addGestureRecognizer:pan];
我想限制可在屏幕上移动的区域。而不是用户能够将视图直接拖到屏幕的一侧,我想限制它的某种边距。我该怎么做?
I would like to restrict the area this can be moved on screen. Rather than the user be able to drag the view right to the side of the screen, I want to restrict it by a margin of some sort. How can I do this?
另外,旋转后如何处理?
Also, how is this then handled when rotated?
编辑---
#pragma mark - Gesture Recognizer
-(void)handlePan:(UIPanGestureRecognizer *)gesture {
NSLog(@"Pan Gesture");
gesture.view.center = [gesture locationInView:self.view];
}
这是我当前处理平移的方法。我需要做的是继续按中心点移动图像视图,并在靠近屏幕边缘时将其移动限制为50。
This is my current method to handle the pan. What I need to do is continue to move the imageview by the center point and also restrict its movement when close to the edge of the screen by 50 for example.
推荐答案
一个可能的解决方案是在你的handlePan方法中,检查屏幕上点的位置,如果它在你想要限制的范围内,则只提交更改。
One possible solution to this is in your handlePan method, check the location of the point on the screen, and only commit the change if it is within the bounds you wish to restrict it to.
对于前。
-(void) handlePan:(UIGestureRecognizer*)panGes{
CGPoint point = [panGes locationInView:self.view];
//Only allow movement up to within 100 pixels of the right bound of the screen
if (point.x < [UIScreen mainScreen].bounds.size.width - 100) {
CGRect newframe = CGRectMake(point.x, point.y, theImageView.frame.size.width, theImageView.frame.size.height);
theImageView.frame = newframe;
}
}
我相信这个也可以正确处理任何屏幕旋转
I believe this would also correctly handle any screen rotation
编辑
要移动图像视图的中心, handlePan
方法看起来像这样。
To move your image view by the center of its frame, the handlePan
method could look something like this.
-(void)handlePan:(UIPanGestureRecognizer *)gesture {
CGPoint point = [gesture locationInView:self.view];
//Only allow movement up to within 50 pixels of the bounds of the screen
//Ex. (IPhone 5)
CGRect boundsRect = CGRectMake(50, 50, 220, 448);
if (CGRectContainsPoint(boundsRect, point)) {
imgView.center = point;
}
}
检查点是否在您想要的范围内,并且如果是这样,请将图像视图框的中心设置为该点。
Check whether the point is within your desired bounds, and if so, set the center of your image view frame to that point.
这篇关于如何通过Pan手势限制可移动视图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!